开发者

How to avoid null values serialization in HashMap?

开发者 https://www.devze.com 2023-01-04 22:23 出处:网络
I would like to serialize a HashMap as a string through the Jackson J开发者_开发知识库SON processor.

I would like to serialize a HashMap as a string through the Jackson J开发者_开发知识库SON processor. 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. It works fine only for POJO if configure the Jackson like this:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);


For what it's worth, Jackson 1.6 will have this:

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.

EDIT: as per note on comments, this is for Jackson 1.x; Jackson 2.x has matching SerializationFeature


Here is the latest annotation for ignoring the NULL fields

@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)


Using Jackson 2.1.2 I have found that I can annotate the class with @JsonInclude(Include.NON_NULL) so that nulls are not serialized at all.


Or you can annotate your bean with @JsonWriteNullProperties(false) which will


With latest Jackson version, on the ObjectMapper, you can do:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号