首页 > 解决方案 > Java 根据 REST 调用显示/隐藏对象字段

问题描述

是否可以根据 REST 调用配置 Item 类以显示和隐藏特定字段?例如,我想在调用时隐藏colorId(和显示categoryIdUser类,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"
    }
}

标签: javajsonxmlspringjackson

解决方案


是的,这可以使用Jackson JSON Views和方法ObjectMapper#writerWithView

您只需要ObjectMapper为两个控制器配置不同的配置就可以了

下面是杰克逊 JSON 视图的一个示例,我们注意到它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;
}

推荐阅读