如何避免HashMap中的空值序列化?

发布于 2024-09-07 15:23:43 字数 400 浏览 6 评论 0原文

我想通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

万水千山粽是情ミ 2024-09-14 15:23:43

无论如何,Jackson 1.6 都会有这样的功能:

objectMapper.configure(SerializationConfig.WRITE_NULL_MAP_VALUES, false);

它确实可以满足您的需求。现有方法仅适用于 bean,并且不会进行更改以确保最大的向后兼容性。

编辑:根据评论的注释,这是针对 Jackson 1.x 的; Jackson 2.x 有匹配的 SerializationFeature

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

拔了角的鹿 2024-09-14 15:23:43

这是忽略 NULL 字段的最新注释

@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)

Here is the latest annotation for ignoring the NULL fields

@JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)

墨落成白 2024-09-14 15:23:43

使用 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.

—━☆沉默づ 2024-09-14 15:23:43

或者您可以使用 @JsonWriteNullProperties(false) 注释您的 bean,这将

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

守不住的情 2024-09-14 15:23:43

使用最新的 Jackson 版本,在 ObjectMapper 上,您可以执行以下操作:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

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

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文