如何解决对象映射器在将对象转换为字符串 Java 时删除空值和空值
响应 api 调用,我发送 Json 类对象作为响应。
我需要这样的响应,而不需要删除空对象。
{
"links": {
"products": [],"packages": []
},"embedded":{
"products": [],"packages": []
}
}
但最终的响应看起来像这样
{
"links": {},"embedded": {}
}
解决方法
需要注意的两点:
-
null
和empty
是不同的东西。 - AFAIK Jackson 配置为默认使用
null
值序列化属性。
确保正确初始化对象中的属性。例如:
class Dto {
private Link link;
private Embedded embedded;
//constructor,getters and setters...
}
class Link {
//by default these will be empty instead of null
private List<Product> products = new ArrayList<>();
private List<Package> packages = new ArrayList<>();
//constructor,getters and setters...
}
确保您的类没有使用此注释 @JsonInclude(JsonInclude.Include.NON_NULL)
扩展另一个类。示例:
//It tells Jackson to exclude any property with null values from being serialized
@JsonInclude(JsonInclude.Include.NON_NULL)
class BaseClass {
}
//Any property with null value will follow the rules stated in BaseClass
class Dto extends BaseClass {
private Link link;
private Embedded embedded;
//constructor,getters and setters...
}
class Link extends BaseClass {
/* rest of the design */
}
如果你有后者并且你不能编辑 BaseClass
那么你可以在特定的类中定义不同的规则:
class Link extends BaseClass{
//no matter what rules are defined elsewhere,this field will be serialized
@JsonInclude(JsonInclude.Include.ALWAYS)
private List<Product> products;
//same here
@JsonInclude(JsonInclude.Include.ALWAYS)
private List<Package> packages;
//constructor,getters and setters...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。