How to avoid null values serialization in HashMap?

前端 未结 5 592
夕颜
夕颜 2021-01-04 06:19

I would like to serialize a HashMap as a string through the Jackson JSON processor. For example:

String strMap = getMapper().writeValueAsString(myHashMap);
r         


        
相关标签:
5条回答
  • 2021-01-04 07:01

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

    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    0 讨论(0)
  • 2021-01-04 07:10

    Here is the latest annotation for ignoring the NULL fields

    @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)

    0 讨论(0)
  • 2021-01-04 07:10

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

    0 讨论(0)
  • 2021-01-04 07:11

    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

    0 讨论(0)
  • 2021-01-04 07:14

    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.

    0 讨论(0)
提交回复
热议问题