I am trying to create json with spring boot.
class:
public class Person {
private String name;
private PersonDetails details;
// getters and
-
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 {
public PersonDetailsSerializer() {
this(null);
}
public PersonDetailsSerializer(Class 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;
}
讨论(0)
- 热议问题