本文介绍了使用JSON对象中的类型将JSON反序列化为POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有多态类型的jackson将JSON解析为POJO。

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

我有以下JSON,我想将其反序列化为POJO。
我创建了包装类来解析所有JSON值,但是我遇到了geometry和geometryType对象的问题。

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.

我创建了POJO每种类型的几何,我想使用geometryType中的值将geometry中的值解析为不同的Java类,具体取决于geometryType的值。例如:如果geometryType ='geometryPolygon',那么我想将geometry解析为Polygon类。

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.

我知道它可能带有注释@JsonTypeInfo并使用属性来为我的POJO选择正确的子类型,但在我的情况下,type实际上是在一个不同的对象中,而不是像我在网上看到的所有其他教程一样在同一个JSON对象中。

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.

任何帮助将不胜感激。

{
"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], .........]]
        }
    }
]
}

POJO类的示例:

class Polygon extends Geometry { ... }
class Polyline extends Geometry {...}


推荐答案

看一下



// 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;

参见:




这篇关于使用JSON对象中的类型将JSON反序列化为POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:09