java根据rest调用显示/隐藏对象字段

vd2z7a6w  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(387)

是否可以根据rest调用配置item类来显示和隐藏特定字段?比如我想躲起来 colorId (并展示) categoryId )从 User 调用时的类 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"
    }
}
wljmcqd8

wljmcqd81#

是的,这可以通过jackson json视图和方法实现 ObjectMapper#writerWithView .
您只需要配置 ObjectMapper 两个控制器都不一样,很好
jacksonjson视图的一个例子如下,我们注意到 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;
}
sdnqo3pr

sdnqo3pr2#

我通过创建以下视图解决了这个问题:

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 在你的回答中你需要定义 @JsonView(View.Parent.class)GroupedItem 以及)
最后,如果您使用的是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"
}

相关问题