@JsonTypeInfo和UnrecognizedPropertyException“type”反序列化Geojson

时间:2016-04-05 12:54:57

标签: jackson geojson

我需要反序列化geojson。 Json-example“Polygon”我来自:http://geojson.org/geojson-spec.html#id4

String polygonJson = "{ \"type\": \"Polygon\",\n" +
        "    \"coordinates\": [\n" +
        "      [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]\n" +
        "      ]\n" +
        "   }";


Polygon pol = new ObjectMapper().readValue(polygonJson, Polygon.class); // fails :-(

方法readValue失败,显示:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "type" (class org.geojson.Polygon), not marked as ignorable (5 known properties: "interiorRings", "crs", "bbox", "coordinates", "exteriorRing"])
 at [Source: { "type": "Polygon",
    "coordinates": [
      [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
      ]
   }; line: 1, column: 12] (through reference chain: org.geojson.Polygon["type"])

在org.geogson库中实现父类:

@JsonTypeInfo(property = "type", use = Id.NAME)
@JsonSubTypes({ @Type(Feature.class), @Type(Polygon.class), @Type(MultiPolygon.class), @Type(FeatureCollection.class),
        @Type(Point.class), @Type(MultiPoint.class), @Type(MultiLineString.class), @Type(LineString.class),
                @Type(GeometryCollection.class) })
@JsonInclude(Include.NON_NULL)
public abstract class GeoJsonObject implements Serializable {...}

它使用名为'type'的属性来查找json字符串表示的实际类。 为什么这个属性无法识别?

1 个答案:

答案 0 :(得分:0)

好的,你的问题是你没有给@Type注释提供足够的信息。您需要添加名称,因此将其更改为如下所示,它应该有效:

@JsonSubTypes({ 
    @Type(value = Feature.class, name = "Feature"), 
    @Type(value = Polygon.class, name = "Polygon")
    ... and so on!