Jackson Mapper serialize empty object instead of null

后端 未结 3 1098
梦毁少年i
梦毁少年i 2021-01-14 11:54

Say I have classes Foo

public class Foo {
    private Bar bar;
}

and Bar

public class Bar {
    private String fizz;
    pr         


        
3条回答
  •  梦毁少年i
    2021-01-14 12:25

    I was also required to produce such a structure for legacy client compatibility, here is my solution (depends on Spring Boot since uses @JsonComponent annotation)

    Create "special object" that will be treated as empty

    public class EmptyObject {
    }
    

    Create property in your model

    @JsonProperty("data")
    private EmptyObject data = new EmptyObject();
    
    public EmptyObject getData() {
        return data;
    }
    

    Create serializer that will process empty object above

    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.ser.std.StdSerializer;
    import com.sevensenders.datahub.api.service.response.model.EmptyObject;
    import org.springframework.boot.jackson.JsonComponent;
    
    import java.io.IOException;
    
    @JsonComponent
    public class EmptyObjectSerializer extends StdSerializer {
    
        public EmptyObjectSerializer() {
            this(null);
        }
    
        public EmptyObjectSerializer(Class t) {
            super(t);
        }
    
        @Override
        public void serialize(EmptyObject value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            // to maintain AF compatible format it is required to write {} instead of null
            gen.writeStartObject();
            gen.writeEndObject();
        }
    }
    

    Output:

    {
      ...
      "data": {}
    }
    

提交回复
热议问题