为了响应api调用,我将发送Json class Object作为响应。
我需要这样的响应,而不会删除空对象。
{
"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...
}