Json to pojo unmarshaler with android的polymorph classes

时间:2010-10-25 20:00:36

标签: android json polymorphism

我有休息和安卓的问题, 问题是我在示例中有一个传输对象Human,它由Male和Female扩展,我想使用json作为人类对象的传输。 如果我使用标准的序列化对象,我通常会这样做

if(human instanceof Male.class){}
else if(human instance of Female.class){}
else{ throw new RuntimeException("incorrect class")}

我如何在Android中实现这个休息? 我见过不支持多态性的Gson和Jaskson, 在服务器端,我们使用Apache CXF进行休息,使用jax-rs注释 想法/以前的经历??

1 个答案:

答案 0 :(得分:0)

我不知道执行反序列化的任何自动方法,但一种解决方案是为您的JSON使用“duck typing”解析器。

假设以下

class Human {
    public Human(JSONObject jo) {
        // Parse out common json elements
    }
}

class Male {
    private boolean hasMaleParts;
    public Male(JSONObject jo) {
        super(jo);
        // Parse out male only parts
    }
}

class Female {
    private boolean hasFemaleParts;
    public Female(JSONObject jo) {
        super(jo);
        // Parse out female only parts
    }
}

使用这三个类,在您的网络访问代码中的某个位置,有一个方法可以键入您返回的JSON并返回相应的对象。

public Human typeJson(JSONObject jo) {
    if(jo.hasBoolean(hasMaleParts))
        return new Male(jo);
    else if(jo.hasBoolean(hasFemaleParts))
        return new Female(jo);
    else
        throw new RuntimeException("Unable to determine data type");
}

在此示例中,hasMalePartshasFemaleParts是任意布尔标志,但是,在许多情况下,您可以(更恰当地)使用标识属性键入它。因此,如果您尝试区分MotorcycleCar,则可以选中number_of_wheels