问题: 创建Include.NON_NULL
时是否可以覆盖POJO中定义的ObjectMapper
?
说明:
假设我有一个POJO如下:
@JsonInclude(Include.NON_NULL)
class POJO {
String name;
String description;
//Constructors, Getters & Setters, etc
}
如下所示的测试课程:
class Main {
public static void main(String args[]) {
POJO p = new POJO();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.setSerializationInclusion(Include.ALWAYS)
.writerWithDefaultPrettyPrinter()
.writeValueAsString(p);
//jsonString should contain empty name & description fields, but they doesn't
}
}
答案 0 :(得分:2)
您可以使用混合,因为它优先于注释。
@JsonInclude(JsonInclude.Include.ALWAYS)
public class MixIn {
}
并将其添加到映射器
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(POJO.class, MixIn.class);
结果将是
{"name":null,"description":null}