对象映射器在将对象转换为字符串时删除空值和空值 Java

Object mapper removing empty and null values when converting object to string Java

响应 api 调用,我将发送 Json Class 对象作为响应。

我需要这样的响应,而不会删除空对象。

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

但最终响应看起来像这样

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

需要注意两点:

  1. nullempty 是不同的东西。
  2. 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...
}

确保您的 classes 没有使用此注释 @JsonInclude(JsonInclude.Include.NON_NULL) 扩展另一个 class。示例:

//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 那么您可以在特定的 classes 中定义不同的规则:

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...
}