Jackson序列化:忽略未初始化的int

编程入门 行业动态 更新时间:2024-10-12 14:23:16
本文介绍了Jackson序列化:忽略未初始化的int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

现在首先,我已经在该网站上阅读了其他答案以及有关杰克逊序列化的其他答案,但它们都提供了忽略null字段的方法.但是,在Java中,int不能为null.

Now first off, I've read some other answers on this site and others about jackson serialisation but they all provide methods for ignoring null fields. In Java, however, int cannot be null.

我正在尝试ObjectMap一个Java对象转换为Json,但是忽略任何null字段.这适用于字符串,但是int如果未初始化,最终将采用0的值,并且由于0不是null,因此不会忽略该字段.

I am trying to ObjectMap a java object to convert to Json but to ignore any null fields. This works for strings but ints end up taking on a value of 0 if uninitialised, and since 0 is not null the field is not ignored.

private ObjectWriter mapper = new ObjectMapper().writer(); private myClass data = new myClass(); //class contains a string and int variable data.setNumber(someInt); //set values data.setString(someString); String Json = mapper.writeValueAsString(data);

请问有人对此有何启示?

Can anyone shed some light on this please?

为澄清起见,我尝试使用Integer类作为数据类型,但导致转换为Json字符串时引发JsonProcessingException.

To clarify, I have tried using the Integer class as the data type but causes the conversion to a Json string to throw a JsonProcessingException.

推荐答案

使用Jackson JsonInclude批注:

Using the Jackson JsonInclude annotation:

@JsonInclude(Include.NON_DEFAULT)

解决以下问题:未分配的原始类型始终采用默认值;在这种情况下,未分配的int变为0,随后将被忽略.

works around the problem where unassigned primitive types always assumes a default value; in this case, unassigned ints become 0 and are subsequently ignored.

更多推荐

Jackson序列化:忽略未初始化的int

本文发布于:2023-10-26 07:09:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   序列化   Jackson   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!