2

I'm trying to parse JSON to POJO using jackson with polymorphic types.

I have the following JSON which I'd like to deserialize to a POJO. I have created wrapper classes to parse all JSON values, but I have problems with the "geometry" and "geometryType" objects.

I have created POJO's for each type of geometry, and I'l like to use the value from "geometryType" to parse the value from "geometry" to different Java class depending on the value of "geometryType". E.g.: if geometryType = 'geometryPolygon' then I'll like to parse "geometry" to Polygon class.

I know its possible with annotation @JsonTypeInfo and using a property to choose the correct subtype for my POJO, but in my case, the "type" is actually in a different object, and not inside the same JSON object like all the other tutorials I saw online.

Any help will be appreciated.

{
"results": [{
        "layerId": 3,
        "layerName": "Parcels",
        "displayFieldName": "LAND_CO",
        "value": "0",
        "attributes": {
            "Feature identifier": "6",
            "SHAPE": "Polygon",
            "PROPERTY_I": "5006",
            "LANDUSE_CO": "0",
            "ZONING": "1",
            "PARCEL_ID": "6363",
            "Res": "Non-Residential",
            "Zoning_simple": "Null",
            "SHAPE_Length": "3594.570779",
            "SHAPE_Area": "112648.196175"
        },
        "geometryType": "geometryPolygon",
        "geometry": {
            "rings": [[[-85.802587291351813, 32.394007668298649], .........]]
        }
    }
]
}

Example of POJO classes:

class Polygon extends Geometry { ... }
class Polyline extends Geometry {...}
octavm
  • 23
  • 6

2 Answers2

0

Have a look at examples with JsonTypeInfo.As.EXTERNAL_PROPERTY

Inclusion mechanism similar to PROPERTY, except that property is included one-level higher in hierarchy, i.e. as sibling property at same level as JSON Object to type. Note that this choice can only be used for properties, not for types (classes). Trying to use it for classes will result in inclusion strategy of basic PROPERTY instead.

// Polygon and Polyline extends Geometry.
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
        property = "geometryType")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "geometryPolygon", value = Polygon.class),
    @JsonSubTypes.Type(name = "geometryPolyline", value = Polyline.class),
    ....})
private Geometry geometry;

See:

Michal Foksa
  • 11,225
  • 9
  • 50
  • 68
0

You can use this amazing tool for converting your JSON to POJO. http://www.jsonschema2pojo.org/

Raj Suvariya
  • 1,592
  • 3
  • 14
  • 36