java - Java 根据 REST 调用显示/隐藏对象字段
问题描述
是否可以根据 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"
}
}
解决方案
是的,这可以使用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;
}
推荐阅读
- r - 从 R 中的 solr 查询中展平 facet.pivot
- mysql - mysql 中缺少 .MYD 和 .MYI 文件
- java - Java中具有连续整数键的元素的有效映射
- javascript - JavaScript - 动态加载一个类并创建具有特定属性的新实例
- f# - F# 中的 ToString() 覆盖不适用于包含另一种类型的类型
- mysql - 列的不同条目和非不同条目之间的差异
- r - 在 igraph 中绘制网络的问题
- c++ - PCL 中的这些 boost 共享指针初始化是否不同?
- rest - SharePoint Online:尝试使用 SharePoint 应用程序中的 AadHttpClient 连接到受 Azure AD 保护的 .Net Core API 时出现问题
- php - 在 Symfony 4 中通过 Ajax 更改区域设置后的渲染视图