我尝试使用Android上的Jackson解析JSON,如下所示(注意:我不能控制JSON格式 - 格式来自Yammer)
"references": [
{
"type": "user",
"id": 12345678,
"name": "Wex"
},
{
"type": "message",
"id": 12345679,
"body":
{
"plain":"A short message"
}
},
{
"type": "thread",
"id": 12345670,
"thread_starter_id": 428181699
}
]
问题是references
中的每个条目都是具有不同属性的不同类型的对象。作为一个开始,我得到了:
public static class Reference
{
public String type;
public String id;
}
我宁愿避免将所有潜在属性放在一个对象中,如:
public static class Reference
{
public static class Body
{
public String plain;
}
public String type;
public String id;
public String name;
public Body body;
public String thread_starter_id;
}
并且想要使用根据type
值创建的单独类,如:
public static class ReferenceUser extends Reference
{
public String name;
}
public static class ReferenceMessage extends Reference
{
public static class Body
{
public String plain;
}
public Body body;
}
public static class ReferenceThread extends Reference
{
public String thread_starter_id;
}
那么......让杰克逊像这样解析JSON的最好方法是什么?
我目前正在解析它,就像这样:
ObjectMapper mapper = new ObjectMapper();
Reference[] references = mapper.readValue(json, Reference[].class);
答案 0 :(得分:3)
杰克逊你可以做这样的事情:
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(name = "user", value = ReferenceUser.class),
@JsonSubTypes.Type(name = "message", value = ReferenceMessage.class),
@JsonSubTypes.Type(name = "thread", value = ReferenceThread.class)
})
public class Reference {
int id;
String name;
}
这样你就会生成子类。
约翰