Do not include empty object to Jackson

前端 未结 1 1657
轮回少年
轮回少年 2021-01-28 09:45

I am trying to create json with spring boot.

class:

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

//     getters and         


        
1条回答
  •  时光取名叫无心
    2021-01-28 10:29

    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 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题