[英]How to ignore empty Objects “{}” but not empty Strings in ObjectMapper?
I need to serialize (ignoring empty objects ("{}")) non-structured object which can have any content. 我需要序列化(忽略空对象(“{}”))非结构化对象,它可以包含任何内容。
From version 2.9.X FasterXML have changed logic of it work for (Include.NON_EMPTY). 从版本2.9.X FasterXML改变了它的逻辑(Include.NON_EMPTY)。 In older version it had worked as I need.
在旧版本中它可以按我的需要工作。 But now it is ignoring empty strings too.
但现在它也忽略了空字符串。
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Lets suppose that we have next java object (for convenience it will look like a JSON): 让我们假设我们有下一个java对象(为方便起见,它看起来像一个JSON):
{
"mapA": {},
"listA": ["",
{
"emptyString": "",
"string": "some text"
},
{}
],
"emptyString": "",
"mapB": {
"emptyString": "",
"mapC": {}
}
}
Converting it to JsonNode: 将其转换为JsonNode:
mapper.convertValue(/*our Object*/, JsonNode.class);
Desired output(Again for convenience it will look like a JSON): 期望的输出(为方便起见,它看起来像JSON):
{
"listA": ["",
{
"emptyString": "",
"string": "some text"
}
],
"emptyString": "",
"mapB": {
"emptyString": ""
}
}
I used Include.CUSTOM
: 我使用了
Include.CUSTOM
:
private static class ExludeEmptyObjects{
@Override
public boolean equals(Object o) {
if (o instanceof Map) {
return ((Map) o).size() == 0;
}
if (o instanceof Collection) {
return ((Collection) o).size() == 0;
}
return false;
}
}
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setDefaultPropertyInclusion(Value.construct(Include.NON_EMPTY, Include.CUSTOM, null, ExludeEmptyObjects.class));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.