如何避免HashMap中的空值序列化?
我想通过 Jackson JSON 处理器将 HashMap 序列化为字符串。 例如:
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]}
我不知道如何禁用 Map 的空值序列化。如果像这样配置 Jackson,则仅适用于 POJO:
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
I would like to serialize a HashMap as a string through the Jackson JSON 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
无论如何,Jackson 1.6 都会有这样的功能:
它确实可以满足您的需求。现有方法仅适用于 bean,并且不会进行更改以确保最大的向后兼容性。
编辑:根据评论的注释,这是针对 Jackson 1.x 的; Jackson 2.x 有匹配的
SerializationFeature
For what it's worth, Jackson 1.6 will have this:
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
这是忽略 NULL 字段的最新注释
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
Here is the latest annotation for ignoring the NULL fields
@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
使用 Jackson 2.1.2 我发现我可以用以下方式注释该类
@JsonInclude(Ininclude.NON_NULL)
以便 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.或者您可以使用 @JsonWriteNullProperties(false) 注释您的 bean,这将
Or you can annotate your bean with @JsonWriteNullProperties(false) which will
使用最新的 Jackson 版本,在 ObjectMapper 上,您可以执行以下操作:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
With latest Jackson version, on the ObjectMapper, you can do:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);