Deserialize JSON with wrapped JSON inside a String using Jackson

Viewed 325

I am receiving a mix of JSON and string-wrapped JSON. E.g.:

{
  "shapes": [
    {
      "type": "1",
      "shape": "{\"w\":3,\"h\":6}"
    },
    {
      "type": "2",
      "shape": "{\"radius\":5}"
    }
  ]
}

I want to deserialize it with different object types.

abstract class Shape {
}

@Data
class Rectangle extends Shape {
    private int w;
    private int h;
}

@Data
class Circle extends Shape {
    private int radius;
}

@Data
class NodeParent {

    private Integer type;

    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
    @JsonSubTypes({
            @JsonSubTypes.Type(value = Rectangle.class, name = "1"),
            @JsonSubTypes.Type(value = Circle.class, name = "2")
    })
    private Shape shape;
}

@Data
class Root {

    private List<NodeParent> shapes;

}

This approach works with normal JSON (without that String wrapping)

But for my payload is fails, as it sees a String inside "shape". I can use a custom Deserializer for this. But then I would have to map all types there. I would've preferred using annotations.

Could this be done?

0 Answers
Related