[英]How to avoid null values serialization in HashMap?
I would like to serialize a HashMap as a string through the Jackson JSON processor. 我想通过Jackson JSON处理器将HashMap序列化为字符串。 For example:
例如:
String strMap = getMapper().writeValueAsString(myHashMap);
result output -> {"r_id":6,"a_am":null,"smb":"Submit","a_li":null,"l_id":878,"pos":[1345,1346,1347]}
I don't know how to disable null values serialization for Map. 我不知道如何为Map禁用空值序列化。 It works fine only for POJO if configure the Jackson like this:
如果像这样配置Jackson,它仅对POJO起作用:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
For what it's worth, Jackson 1.6 will have this: 对于它的价值,Jackson 1.6将具有以下功能:
objectMapper.configure(SerializationConfig.WRITE_NULL_MAP_VALUES, false);
which does do what you want. 哪个可以做您想要的。 Existing method only works for beans, and is not being changed to ensure maximum backwards compatibility.
现有方法仅适用于bean,并且不会进行更改以确保最大程度的向后兼容性。
EDIT: as per note on comments, this is for Jackson 1.x; 编辑:根据注释的注释,这是针对Jackson 1.x的; Jackson 2.x has matching
SerializationFeature
Jackson 2.x具有匹配的
SerializationFeature
Here is the latest annotation for ignoring the NULL fields 这是用于忽略NULL字段的最新注释
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
使用Jackson 2.1.2,我发现可以使用@JsonInclude(Include.NON_NULL)
注释该类,以便根本不对null进行序列化。
或者,您可以使用@JsonWriteNullProperties(false)注释您的bean,这将
With latest Jackson version, on the ObjectMapper, you can do: 使用最新的Jackson版本,在ObjectMapper上,您可以执行以下操作:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.