Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing single json entry to multiple objects with Gson
    text
    copied!<p>I have a json response that looks like this:</p> <pre><code>{ "id":"001", "name":"Name", "param_distance":"10", "param_sampling":"2" } </code></pre> <p>And I have two classes: Teste and Parameters</p> <pre><code>public class Test { private int id; private String name; private Parameters params; } public class Parameters { private double distance; private int sampling; } </code></pre> <p>My question is: is there a way to make Gson understand that some of the json attributes should go to the Parameters class, or the only way is to "manually" parse this ?</p> <h2>EDIT</h2> <p>Well, just to make my comment in @MikO's answer more readable:</p> <p>I'll add a list of an object to the json output, so json response should look like this:</p> <pre><code> { "id":"001", "name":"Name", "param_distance":"10", "param_sampling":"2", "events":[ { "id":"01", "value":"22.5" }, { "id":"02", "value":"31.0" } ] } </code></pre> <p>And the Deserializer class would look like this:</p> <pre><code>public class TestDeserializer implements JsonDeserializer&lt;Test&gt; { @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&lt;List&lt;Event&gt;&gt;(){}.getType(); List&lt;Event&gt; eventList = eventGson.fromJson(obj.get("events"), eventsType); test.setEvents(eventList); return test; } } </code></pre> <p>And doing:</p> <pre><code>GsonBuilder gBuilder = new GsonBuilder(); gBuilder.registerTypeAdapter(Test.class, new TestDeserializer()); Gson gson = gBuilder.create(); Test test = gson.fromJson(reader, Test.class); </code></pre> <p>Gives me the test object the way I wanted. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload