对象Map程序在将对象转换为字符串java时删除空值和空值

5w9g7ksd  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(469)

为了响应api调用,我将json类对象作为响应发送。
我需要这样的回应,而不是空的对象被删除。

{
   "links": {
      "products": [],
     "packages": []
    },
   "embedded":{
      "products": [],
      "packages": []
    }
}

但最终的React是这样的

{
 "links": {},
 "embedded": {}
}
enyaitl3

enyaitl31#

要注意两件事: 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...
}

相关问题