如何在使用Jackson 1.5转换为JSON时排除对象中的空值?

时间:2014-05-09 07:52:02

标签: java json jackson

我正在尝试使用Jackson库1.5创建一个Json对象,但也获得了具有Null值的对象。

如何摆脱Null值?

以下是我正在使用的代码。

    package com.test;
        public class Sample {

            public String name;

            public String surname;



            public Sample(String name, String surname) {
                this.name = name;
                this.surname = surname;
            }

            public String getName() {
                return name;
            }

            public String getSurname() {
                return surname;
            }


        }


        public static void main(String[] args){
        Sample sample = new Sample("Sam", null);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false);
        System.out.println(mapper.writeValueAsString(restRetrieveQuoteResponse));

        }
}

这里的问题是mapper.configure(SerializationConfig.Feature.WRITE_NULL_PROPERTIES, false); 不推荐使用WRITE_NULL_PROPERTIES。

我试图找到替代方案,但找不到。大多数可用的解决方案都是使用Jackson 2.2。有人可以帮我解决1.5吗?

我查看了herehere

4 个答案:

答案 0 :(得分:3)

你到处寻找,但在javadoc它声明使用inclusion作为经验法则,大多数弃用的方法都说明了使用什么而不是它们

答案 1 :(得分:2)

尝试使用

mapper.setSerializationInclusion(Include.NON_NULL);

答案 2 :(得分:1)

使用以下内容注释您的字段或类:

@JsonWriteNullProperties(false)

http://wiki.fasterxml.com/JacksonAnnotations

答案 3 :(得分:1)

macziknasz中的链接回答需要登录,所以我只是在这里发布我的解决方案:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);