sameer sameer - 10 months ago 36
Java Question

How to use Gson to parse multiple types of payloads

I am using GSON parser to parse Http Response with JSON format as:

{ "type" : "A1", "payload": <Format as per type A1> }
{ "type" : "A2", "payload": <Format as per type A2> }

I don't have control over JSON output as I am writting only http client

I have defined base class as:

class Base {
String type;
Object payload;

Gson g = new Gson();
Base baseObj = gson.fromJson(response, Base.class);
// Need to cast and access baseObj.payload to specific class

But now I want to cast "Object payload" to specific class and access its member variables


well for nested objects in a JSON response you don't control of, you have to write a deserializer. See for GSON specific implementation:

In theory, I don't really recommend this, because it's hackish, but you could also make it work depending if its throw-away code by doing something simple like below.

class Baselike {
    String type;
    String payloadStr;

class Payload
    public int foo; // whatever the format is
    public String bar;

Gson g = new Gson();
Baselike baseObj = gson.fromJson(response, Baselike.class);
Payload payloadObj = gson.fromJson(baseObj.payloadStr, Payload.class);