我有一个类的对象列表,我将其作为 json 呈现给浏览器。现在,如果不满足某些条件,我想从 json 响应中排除对象中的某些属性。
因此,这些属性对于列表中的某些对象将存在,而对于该列表的其他对象将不存在。
我如何实现这一目标?
我的是一个 Spring Boot 应用程序。正在使用 jackson 。
我使用 Transformer 将 Entity 转换为 Bean,然后使用 ResponseEntity 将 bean 转换为 json。
请提出可能的解决方案。
谢谢。
最佳答案
将这些值(您想要排除的值)设置为 null,然后使用 @JsonInclude
注释来抑制所有 null 值。
@JsonInclude(Include.NON_NULL) class Foo { String bar; }
您也可以排除特定字段的 null
值(而不是排除整个对象的 null 值)
public class Foo { private String field1; private String field2; @JsonInclude(Include.NON_NULL) private String field3; ... ... }
在版本 2.x+ 中,此注释的语法为:
@JsonInclude(JsonSerialize.Inclusion.NON_NULL)
或者您也可以设置全局选项:
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
在 Spring 项目中,objectMapper
是类 ObjectMapper
的单例实例,您可以使用 @Autowired
或从 ApplicationContext 获取它
关于json - 根据某些条件排除 json 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276232/