Search code examples
serializationjacksonpojogeojson

Deserialize GeoJSON with Jackson Parser


I'm trying to deserialize GeoJSON into corresponding POJOs. I have a Java Object for each GeoJSON Type (Point, LineString, Polygon etc...). I would like to make Jackson use the type field of the GeoJSON Entity to use the corresponding Java class. For example lets say I have the following GeoJSON Entities:

{ "type": "Point", "coordinates": [100.0, 0.0] }

{ "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }

{ 
"type": "Polygon", "coordinates": [
    [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ],
    [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ]
  ]
}

For the first object Jackson should use the point class and should deserialize the coordinates field accordingly. For the second object Jackson should use the LineString object and for the third the polygon object.

I know you can write custom deserializers in Jackson but I have only seen those for single object fields. In my case I think I have to write a deserializer for the entire GeoJSON Entity because depending on the type field the whole representation changes.

Perhaps someone can give me a hint on what to do in this case? Perhaps there is some clever trick I haven't read about?

Thanks.


Solution

  • Why would you need custom handler? You do need to use @JsonTypeInfo annotation (property "type"; method "As.NAME") to get automatic polymorphic type handling; and sub-classes must define name to use with @JsonTypeName. But other than that it seems doable. Structure of 'coordinates' property seems to vary, so you need to model that for separate sub-classes.