【发布时间】:2017-06-14 20:04:33
【问题描述】:
我是 Jackson 的新手,使用通用字段反序列化 JSON 时遇到问题。这是我想使用 Jackson 解析的 JSON。
{
"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 元素可能只包含 strings 或 objects 或两者。
这里是 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
}
我尝试使用 JsonSubTypes 注释将 JSON 映射到 POJO,所以如果 type 等于 complex 那么 JSON 应该映射到 Content 类,对于 simple 类型,映射类应该是 @987654337 @ 目的。问题是杰克逊将complex 内容转换为LinkedHashMap 我不想要的内容。对于simple 的内容没有问题,它会被转换为String,但我认为Jackson 使用内部逻辑来映射这种正确的方式。
如果我尝试使用JsonDeserialize 注释,则不会调用任何反序列化器方法。就像杰克逊忽略了注释,自己做事一样。
我在哪里做错了?我应该怎么做才能将complex内容解析为Content POJO?
【问题讨论】:
标签: java json generics jackson deserialization