[英]How do I parse a JSON array into different objects using Jackson on Android?
I'm trying to parse JSON like the following into object using Jackson on Android (Note: I'm not in control of the JSON format - the format comes from Yammer) 我正在尝试在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
}
]
The problem is that each entry in references
is a different type of object with different properties. 问题在于
references
中的每个条目都是具有不同属性的不同类型的对象。 As a start I've got: 首先,我得到了:
public static class Reference
{
public String type;
public String id;
}
I'd rather avoid putting all potential properties in one object like: 我宁愿避免将所有潜在属性放在一个对象中,例如:
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;
}
And want to use separate classes that are created dependant on the type
value like: 并希望使用根据
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;
}
So... what's the best way of getting Jackson to parse the JSON like that? 那么...让Jackson像这样解析JSON的最佳方法是什么?
I'm currently parsing it quite simply like this: 我目前正在像这样简单地解析它:
ObjectMapper mapper = new ObjectMapper();
Reference[] references = mapper.readValue(json, Reference[].class);
you can do something like this with Jackson: 您可以使用Jackson进行以下操作:
@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;
}
This way you will generate subclasses. 这样,您将生成子类。
John 约翰
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.