Do not include empty object to Jackson

杀马特。学长 韩版系。学妹 提交于 2021-02-17 05:11:33

问题


I am trying to create json with spring boot.

class:

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

//     getters and setters...
}

impletentation:

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

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

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

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

Update 1:

I'm using Jackson 2.9.6


回答1:


Without a custom serializer, jackson will include your object.

Solution 1 : Replace new object with null

person.setDetails(new PersonDetails());

with

person.setDetails(null);

and add

@JsonInclude(Include.NON_NULL)
public class Person {

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);
    }
}

and in your PersonDetails

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


来源:https://stackoverflow.com/questions/53234727/do-not-include-empty-object-to-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!