问题
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