是否可以配置依赖于REST调用来显示和隐藏特定字段的Item类?例如,在调用colorId时,我希望隐藏User类中的XmlController (并显示XmlController),在调用JsonController时则相反。
项目类
@Getter
@Setter
@NoArgsConstructor
public class Item
{
private Long id;
private Long categoryId; // <-- Show field in XML REST call and hide in JSON REST call
private Long colorId; // <-- Show field in JSON REST call and hide in XML REST call
private Long groupId;
@JacksonXmlProperty(localName = "item")
@JacksonXmlElementWrapper(localName = "groupItems")
private List<GroupedItem> item;
}JSON控制器
@RestController
@RequestMapping(
path = "/json/",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class JsonController
{
@Autowired
private Service service;
@RequestMapping(path = "{colorId}")
public Item getArticles(@PathVariable("colorId") Long colorId)
{
return service.getByColor(colorId); // returns JSON without "categoryId"
}
}XML控制器
@RestController
@RequestMapping(
path = "/xml/",
produces = MediaType.APPLICATION_XML_VALUE)
public class XmlController
{
@Autowired
private Service service;
@RequestMapping(path = "{categoryId}")
public Item getArticles(@PathVariable("categoryId") Long categoryId)
{
return service.getByCategory(categoryId); // returns XML without "colorId"
}
}发布于 2021-04-07 10:55:21
我通过创建以下视图来解决这个问题:
public class View
{
public static class Parent
{
}
public static class Json extends Parent
{
}
public static class Xml extends Parent
{
}
}使用此配置,可以将类设置为:
@Getter
@Setter
@NoArgsConstructor
@JsonView(View.Parent.class)
public class Item
{
private Long id;
@JsonView(View.Xml.class) // <-- Show field in XML REST call and hide in JSON REST call
private Long categoryId;
@JsonView(View.Json.class) // <-- Show field in JSON REST call and hide in XML REST call
private Long colorId;
private Long groupId;
@JacksonXmlProperty(localName = "item")
@JacksonXmlElementWrapper(localName = "groupItems")
private List<GroupedItem> item;
}(注意:如果您想在响应中列出List<GroupedItem> item,也需要在GroupedItem中定义@JsonView(View.Parent.class) )
最后,如果使用Spring,则REST请求(参见问题)可以定义为:
@JsonView(View.Json.class) // or @JsonView(View.Xml.class) in other case
@RequestMapping(path = "{colorId}")
public Item getArticles(@PathVariable("colorId") Long colorId)
{
return service.getByColor(colorId); // returns JSON without "categoryId"
}发布于 2021-04-06 14:49:01
是的,使用Jackson JSON视图和ObjectMapper#writerWithView方法是可能的。
您只需要为两个控制器配置不同的ObjectMapper就可以了
Jackson视图的一个例子是:我们注意到ownerName只能在内部访问,而不是公开访问
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
}https://stackoverflow.com/questions/66970855
复制相似问题