views:

23

answers:

1

Hello, I am having a problem with rest and android, the problem is I have a transport object in example a class Human, which is extended by Male and Female, I want to use json as transport for the human object. if I use standard serialized objects, i would usually do

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

how do I implement this in android with rest? I've seen that Gson and Jaskson which do not support polymorphism, on the server side we're using Apache CXF for rest, with jax-rs annotations Ideas/previous experiences??

A: 

I don't know of any automatic way to perform de-serialization, but one solution is to use a "duck typing" parser for your JSON.

Assume the following

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
    }
}

With these three classes, somewhere in your network access code, have a method which types your returned JSON and returns the appropriate object.

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");
}

In this example hasMaleParts and hasFemaleParts are arbitrary boolean flags, however, in many instances you could (more properly) type it using identifying attributes. So, if you were trying to distinguish between Motorcycle and Car, you might check number_of_wheels.

jwriteclub