不要向杰克逊添加空对象 [英] Do not include empty object to Jackson

查看:69
本文介绍了不要向杰克逊添加空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spring Boot创建json.

I am trying to create json with spring boot.

班级:

public class Person {
    private String name;
    private PersonDetails details;

//     getters and setters...
}

实现:

Person person = new Person();
person.setName("Apple");
person.setDetails(new PersonDetails());

因此,有一个Person实例,其中details为空,而这正是Jackson返回的内容:

So there is a instance of Person with empty details and this is exactly what Jackson is returning:

"person": {
    "name": "Apple",
    "details": {}
}

我想拥有json 而没有空括号{}:

I want to have json without empty brackets {}:

"person": {
    "name": "Apple"
}

这个问题对我没有帮助:

This question's didn't helped me:

  • How to tell Jackson to ignore empty object during deserialization?
  • How to ignore "null" or empty properties in json, globally, using Spring configuration

更新1:

我正在使用Jackson 2.9.6

I'm using Jackson 2.9.6

推荐答案

如果没有自定义序列化程序,杰克逊将包含您的对象.

Without a custom serializer, jackson will include your object.

解决方案1:将新对象替换为空

Solution 1 : Replace new object with null

person.setDetails(new PersonDetails());

使用

person.setDetails(null);

并添加

@JsonInclude(Include.NON_NULL)
public class Person {

解决方案2:自定义序列化程序

Solution 2: Custom serializer

public class PersonDetailsSerializer extends StdSerializer<PersonDetails> {

    public PersonDetailsSerializer() {
        this(null);
    }

    public PersonDetailsSerializer(Class<PersonDetails> t) {
        super(t);
    }

    @Override
    public void serialize(
            PersonDetails personDetails, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        // custom behavior if you implement equals and hashCode in your code
        if(personDetails.equals(new PersonDetails()){
           return;
        }
        super.serialize(personDetails,jgen,provider);
    }
}

和您的PersonDetails

public class Person {
    private String name;
    @JsonSerialize(using = PersonDetailsSerializer.class)
    private PersonDetails details;
}

这篇关于不要向杰克逊添加空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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