首页 > 解决方案 > GeoJson Jackson - 将 JSON 解析为 Java 对象失败

问题描述

我正在将 GeoJSON 文件解析为 Java POJO 类。我发现 GeoJSON Jackson 库似乎与我需要的完全一样。

https://github.com/opendatalab-de/geojson-jackson

我有一个如下 JSON:

    {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "lfdNr": 1,
        "betriebsNummer": 33,
        "nummer": 4,
        "bezeichnung": "TERST",
        "kng": 61062323,
        "nArtCode": "A",
        "nArtB": "ACKERLAND",
        "flaeche": 4.0748
      },
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              15.8867118536754,
              48.4004384452486
            ],
            [
              15.884483831836,
              48.3981983444393
            ],
            [
              15.8847389374202,
              48.3991957290405
            ],
            [
              15.8853143451339,
              48.3991585954555
            ],
            [
              15.8851662097189,
              48.398462039698
            ],
            ....
          ]
        ]
      }
    }
  ]
}

我希望将其用作 FeatureCollection java 对象:

objectMapper.readValue(json, FeatureCollection.class);

我得到以下信息:

    com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct 
    instance of `org.geojson.GeoJsonObject` 
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, 
have custom deserializer, or contain additional type information
 at [Source: (String)"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"lfdNr":1,"betriebsNummer":10086722,"nummer":4,"bezeichnung":"TERST","fskennung":61062323,"nutzungsArtCode":"A","nutzungsArtBezeichnung":"ACKERLAND","flaeche":4.0748},"geometry":{"type":"Polygon","coordinates":[[[15.8867118536754,48.4004384452486],[15.8829132747878,48.4002081767679],["[truncated 2362 chars]; line: 1, column: 251] 
 (through reference chain: org.geojson.FeatureCollection["features"]->java.util.ArrayList[0]->org.geojson.Feature["geometry"])

我认为这是因为类 Geometry 一个泛型类型是:

public abstract class Geometry<T> extends GeoJsonObject

我只使用多边形和点。

任何想法我怎样才能让它工作?

非常感谢!

标签: javajacksongeojsonjson-deserializationobjectmapper

解决方案


您可以通过以下方式阅读此 JSON 内容

GeoJsonObject object = objectMapper.readValue(json, GeoJsonObject.class);
if (object instanceof FeatureCollection) {
    FeatureCollection featureCollection = (FeatureCollection) object;
    ...
}

FeatureCollection由于类上的注释,Jackson 会自动将您的 JSON 示例识别为对象GeoJsonObject

@JsonTypeInfo(property = "type", use = Id.NAME)
@JsonSubTypes({ @Type(Feature.class), ...,  @Type(FeatureCollection.class), ... })
...
public abstract class GeoJsonObject implements Serializable {
    ...
}

推荐阅读