我是新来的杰克逊,并有通用字段反序列化JSON的问题。这是我想用Jackson解析的JSON。如何在运行时泛型中使用Jackson?
{
"topic": {
"headline": {
...
},
"body": [
{
"type": "complex",
"content": {
"player_template": "12345",
"width": 600,
"height": 338,
"url": "http://...",
"caption": "foobar",
"vid": "12345",
"watch_url": "http://...",
"embed_html": "<script..."
},
"preview_image_url": "https://...",
"position": 0
},
{
"content": "foobar",
"type": "simple",
"position": 1
}
],
"type": "some type",
"part": "image",
"box_link": [
{
...
},
...
]
}
}
注意
topic > body > element[0] > content
是object
,但topic > body > element[1] > content
是string
。 body
元素可能只包含string
或object
或两者。
这里是针对body
和content
的Java类。
public class Body<T> {
// @JsonDeserialize(using = ContentDeserializer.class)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = String.class, name = "simple"),
@JsonSubTypes.Type(value = Content.class, name = "complex")
})
@JsonProperty("content")
private T mContent;
@JsonProperty("type")
private String mType;
@JsonProperty("preview_image_url")
private String mPreviewImageUrl;
@JsonProperty("position")
private int mPosition;
// getter and setter
}
public class Content {
@JsonProperty("player_template")
private String mPlayerTemplate;
@JsonProperty("width")
private int mWidth;
@JsonProperty("height")
private int mHeight;
@JsonProperty("url")
private String mUrl;
@JsonProperty("caption")
private String mCaption;
@JsonProperty("vid")
private String mVid;
@JsonProperty("watch_url")
private String mWatchUrl;
@JsonProperty("embed_html")
private String mEmbedHtml;
// getter and setter
}
我尝试映射JSON使用JsonSubTypes
批注POJO,所以如果type
等于complex
然后JSON应该被映射到Content
类,对于simple
类型的映射类应该是String
对象。问题是,杰克逊转换complex
内容到LinkedHashMap
我不想要的。对于simple
内容没有问题,它将被转换为String
,但我认为杰克逊使用内部逻辑来映射这种正确的方式。
如果我尝试使用JsonDeserialize
注释,则不会调用解串器方法。这就像杰克逊忽视注释并做出自己的工作。
我在哪里犯了一个错误?我应该怎么做才能解析complex
内容到Content
POJO?
感谢您的解释,但不幸的是它给出了相同的结果'LinkedHashMap'。 – user2319066