Java 将JSON解组到具有不同字段类型的子类型
我收到一个JSON对象数组,所有对象都有字段内容,但此字段的类型可能不同:Java 将JSON解组到具有不同字段类型的子类型,java,json,jackson,json-deserialization,Java,Json,Jackson,Json Deserialization,我收到一个JSON对象数组,所有对象都有字段内容,但此字段的类型可能不同: [ { "id": "primaryBodyHeader", "type": "RichText", "content": "<h1>Alice's Adventures in Wonderland</h1>" }, { "id": "1027", "type": "RichText",
[
{
"id": "primaryBodyHeader",
"type": "RichText",
"content": "<h1>Alice's Adventures in Wonderland</h1>"
},
{
"id": "1027",
"type": "RichText",
"content": {
"value": "RVMtMTk=",
"contentType": "DynamicContent"
}
}
]
当非文本内容为文本null时,至少我希望将内容映射到文本字段
最多,我希望根据字段内容的类型将不同类型的项映射到不同的子类——TextContentItem、ComplexContentItem等等@JsonSubTypes不能这样做
有没有一种方法可以不用自定义反序列化程序来实现这一点?不用编写自定义反序列化程序,我能想到的最好方法是:
public class LandingPageContentItem {
private String id;
private String type;
private Object content;
}
然后使用ifitem.content instanceof String和ifitem.content instanceof Map从那里处理它。如果不编写自定义反序列化程序,我能想到的最好方法是:
public class LandingPageContentItem {
private String id;
private String type;
private Object content;
}
然后使用ifitem.content instanceof String和ifitem.content instanceof Map从那里处理它。如果您不知道或无法控制内容字段中的内容,那么我建议您像这样映射原始内容
public static class LandingPageContentItem {
private final String id;
private final String type;
private final JsonNode content;
@JsonCreator
public LandingPageContentItem(
@JsonProperty("id") final String id,
@JsonProperty("type") final String type,
@JsonProperty("content") final JsonNode content) {
this.id = id;
this.type = type;
this.content = content;
}
/* some logic here */
}
然后你就可以正常阅读了
ObjectMapper mapper = new ObjectMapper();
List<LandingPageContentItem> items =
mapper.readValue(node, new TypeReference<List<LandingPageContentItem>>() {});
若你们不知道或无法控制内容字段中可能存在的内容,那个么我建议你们像这样映射原始内容
public static class LandingPageContentItem {
private final String id;
private final String type;
private final JsonNode content;
@JsonCreator
public LandingPageContentItem(
@JsonProperty("id") final String id,
@JsonProperty("type") final String type,
@JsonProperty("content") final JsonNode content) {
this.id = id;
this.type = type;
this.content = content;
}
/* some logic here */
}
然后你就可以正常阅读了
ObjectMapper mapper = new ObjectMapper();
List<LandingPageContentItem> items =
mapper.readValue(node, new TypeReference<List<LandingPageContentItem>>() {});
@vsminkov有一个更好的答案。在大多数情况下,JsonNode可能比Object好。@vsminkov有一个更好的答案。在大多数情况下,JsonNode可能比Object更好。