Jackson序列化:忽略未初始化的int [英] Jackson serialization: Ignore uninitialised int

查看:160
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆