How do I parse a JSON array into different objects using Jackson on Android?

核能气质少年 提交于 2020-01-02 09:38:16

问题


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)

"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. 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:

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?

I'm currently parsing it quite simply like this:

ObjectMapper mapper = new ObjectMapper();
Reference[] references = mapper.readValue(json, Reference[].class);

回答1:


you can do something like this with 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



来源:https://stackoverflow.com/questions/25294343/how-do-i-parse-a-json-array-into-different-objects-using-jackson-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!