我正在使用 Jackson 2.4 将对象序列化为 JSON。
当我序列化对象列表时,某些元素为空,结果 JSON
字符串包含一些“空”字符串。
如何防止 "null"
元素被序列化? ObjectMapper
有什么配置吗?我已经设置了 "setSerializationInclusion(Include.NON_NULL)"
!
这是我的代码:
List<String> strings = new ArrayList<>();
strings.add("string 1");
strings.add("string 2");
strings.add(null);
strings.add(null);
序列化后我得到了这个:
[string 1, string 2, null, null]
如何获取不带“null”的 JSON 字符串?
[string 1, string 2]
最佳答案
使用 @JsonInclude注释。
@JsonInclude(Include.NON_NULL)
class Foo {
String bar;
}
编辑
您也可以创建自己的序列化程序。
例如:
public static void main(String[] args) throws JsonProcessingException {
List<String> strings = new ArrayList<>();
strings.add("string 1");
strings.add("string 2");
strings.add(null);
strings.add(null);
ObjectMapper mapper=new ObjectMapper();
mapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
System.out.println(mapper.writeValueAsString(strings));
}
NullSerializer.java
class NullSerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
throws IOException, JsonProcessingException
{
jsonGen.writeFieldName("");
}
}
将打印
["string 1","string 2","",""]
然后你可以删除 jsonGen.writeFieldName("");打印
["string 1","string 2"]
关于java - Jackson - 序列化包含空元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27246955/