Immutable/polymorphic POJO <-> JSON serialization with Jackson

后端 未结 3 1846
南方客
南方客 2021-02-08 06:00

I\'m trying to serialize a immutable POJO to and from JSON, using Jackson 2.1.4, without having to write a custom serializer and with as few annotations as possible. I also like

3条回答
  •  旧巷少年郎
    2021-02-08 06:22

    You could (according to the API) annotate the constructor with @JsonCreator and the parameters with @JsonProperty.

    public class Circle extends Shape {
        public final int radius; // Immutable - no getter needed
    
        @JsonCreator
        public Circle(@JsonProperty("radius") int radius) {
            this.radius = radius;
        }
    }
    
    public class Rectangle extends Shape {
        public final int w; // Immutable - no getter needed
        public final int h; // Immutable - no getter needed
    
        @JsonCreator        
        public Rectangle(@JsonProperty("w") int w, @JsonProperty("h") int h) {
            this.w = w;
            this.h = h;
        }
    }
    

    Edit: Maybe you have to annotate the Shape class with @JsonSubTypes so that the concrete subclass of Shape could be determined.

    @JsonSubTypes({@JsonSubTypes.Type(Circle.class), @JsonSubTypes.Type(Rectangle.class)})
    public abstract class Shape {}
    

提交回复
热议问题