1

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:

Update 1:

I'm using Jackson 2.9.6

Marin
  • 85
  • 4
  • 9
  • Custom serializer/deserializer for ignoring your empty specific object sounds as good solution. So e.g. `@JsonInclude(Include.NON_NULL)` not working in this case because you haven't null object, you have object wich has no attribute filled. Why do you want to ignore empty object in JSON? – jjaros Nov 10 '18 at 11:38

1 Answers1

4

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;
}
Adina Rolea
  • 2,031
  • 1
  • 7
  • 16