使用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 {...}
看一下 JsonTypeInfo.As.EXTERNAL_PROPERTY
类似于PROPERTY的包含机制,但属性包含在一个级别中层次结构更高,即与要输入的JSON对象处于同一级别的同级属性。请注意,此选择只能用于属性,而不能用于类型(类)。尝试将其用于课程将导致基本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;
参见: