Invalid object serialization in json with inheritance and a list of objects when using @JsonFormat

Viewed 137

I have this classes:

Shape:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
        @JsonSubTypes.Type(value = Rectangle.class),
        @JsonSubTypes.Type(value = Circle.class)})
public abstract class Shape {
}

Circle:

@JsonTypeName("circle")
public class Circle extends Shape {
    int radius;
    //getters,setters
}

Rectangle:

@JsonTypeName("rectangle")
public class Rectangle extends Shape {
    private int w;
    private int h;
    //getters,setters
}

View:

@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class View {
    private List<Shape> shapes;
    //getters,setters
}

Main:

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        View view = new View();
        view.setShapes(Arrays.asList(Circle.of(2), Rectangle.of(5,4)));
        String json = new ObjectMapper().writeValueAsString(view);
        System.out.println(json);
    }
}

After serialization, I get this json string:

[[{"circle":{"radius":2}},{"rectangle":{"w":5,"h":4}}]]

I get array in array. Can I get using Jackson following line, using the same structure:

[{"circle":{"radius":2}},{"rectangle":{"w":5,"h":4}}]

I don't want to wrap the list in an array, the list is already an array for me.

0 Answers
Related