I have a json answer that looks like this:
{ "id":"001", "name":"Name", "param_distance":"10", "param_sampling":"2" }
And I have two classes: Teste and Parameters
public class Test { private int id; private String name; private Parameters params; } public class Parameters { private double distance; private int sampling; }
My question is: is there a way to make Gsson understand that some json attributes should go into the Parameters class, or is there the only way to "manually" parse this?
EDIT
Ok, just to make my comment on @MikO more readable:
I will add the object list to the json output, so the json response should look like this:
{ "id":"001", "name":"Name", "param_distance":"10", "param_sampling":"2", "events":[ { "id":"01", "value":"22.5" }, { "id":"02", "value":"31.0" } ] }
And the Deserializer class will look like this:
public class TestDeserializer implements JsonDeserializer<Test> { @Override public Test deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); Test test = new Test(); test.setId(obj.get("id").getAsInt()); test.setName(obj.get("name").getAsString()); Parameters params = new Parameters(); params.setDistance(obj.get("param_distance").getAsDouble()); params.setSampling(obj.get("param_sampling").getAsInt()); test.setParameters(params); Gson eventGson = new Gson(); Type eventsType = new TypeToken<List<Event>>(){}.getType(); List<Event> eventList = eventGson.fromJson(obj.get("events"), eventsType); test.setEvents(eventList); return test; } }
And do:
GsonBuilder gBuilder = new GsonBuilder(); gBuilder.registerTypeAdapter(Test.class, new TestDeserializer()); Gson gson = gBuilder.create(); Test test = gson.fromJson(reader, Test.class);
Gives me a test object the way I wanted.