对于 Spring Boot 1.2.3,如何在 JSON 序列化中设置忽略空值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30042507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For Spring Boot 1.2.3, how to set ignore null value in JSON serialization?
提问by crisli
In the Spring Boot 1.2.3, we can customize the Hymanson ObjectMapper via properties file. But I didn't find a attribute can set Hymanson ignore null value when serialization the Object to JSON string.
在 Spring Boot 1.2.3 中,我们可以通过属性文件自定义 Hymanson ObjectMapper。但是我没有发现在将 Object 序列化为 JSON 字符串时可以设置 Hymanson 忽略空值的属性。
spring.Hymanson.deserialization.*= # see Hymanson's DeserializationFeature
spring.Hymanson.generator.*= # see Hymanson's JsonGenerator.Feature
spring.Hymanson.mapper.*= # see Hymanson's MapperFeature
spring.Hymanson.parser.*= # see Hymanson's JsonParser.Feature
spring.Hymanson.serialization.*=
I want to archive the same code like
我想归档相同的代码
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
采纳答案by ikumen
This was an enhancement for Spring Boot 1.3.0.
这是 Spring Boot 1.3.0 的增强。
So unfortunately you'll need to configure it programmatically on 1.2.3
所以不幸的是你需要在 1.2.3 上以编程方式配置它
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class Shop {
//...
}
回答by cjungel
Add the following line to your application.properties
file.
将以下行添加到您的application.properties
文件中。
spring.Hymanson.default-property-inclusion=non_null
spring.Hymanson.default-property-inclusion=non_null
For versions of Hymanson prior to 2.7:
对于 2.7 之前的 Hymanson 版本:
spring.Hymanson.serialization-inclusion=non_null
spring.Hymanson.serialization-inclusion=non_null
回答by Itay
This was a good solution before deprecation:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
这是弃用之前的一个很好的解决方案:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
But now you should use:
但现在你应该使用:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ClassName {
...
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ClassName {
...
You can take a look here: https://fasterxml.github.io/Hymanson-annotations/javadoc/2.7/com/fasterxml/Hymanson/annotation/JsonInclude.Include.html
您可以在这里查看:https: //fasterxml.github.io/Hymanson-annotations/javadoc/2.7/com/fasterxml/Hymanson/annotation/JsonInclude.Include.html
回答by Bruno Régnier
For Spring Boot 1.4.x, you can include the following line to your application.properties
对于 Spring Boot 1.4.x,您可以在application.properties 中包含以下行
spring.Hymanson.default-property-inclusion=non_null
spring.Hymanson.default-property-inclusion=non_null
回答by Mehul Katpara
Class-wide,
全班,
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyModel { .... }
Property-wide:
物业范围:
public class MyModel {
.....
@JsonInclude(JsonInclude.Include.NON_NULL)
private String myProperty;
.....
}