0

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

2 Answers2

0

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

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);
Community
  • 1
  • 1
0

You can use jackson to deserialize your json to class.

You can write something like this:

ObjectMapper objectMapper = new ObjectMapper(); SampleClass abc= objectMapper.readValue(jsonData, SampleClass .class);

vaski thakur
  • 92
  • 1
  • 9