Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The way to make Gson understand it is to write a custom deserializer by creating a <code>TypeAdapter</code> for your <code>Test</code> class. You can find information in <a href="https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer" rel="nofollow"><strong>Gson's User Guide</strong></a>. It is not exactly a <em>manual parsing</em>, but it is not that different, since you have to tell Gson how to deal with each JSON value...</p> <p>It should be something like this:</p> <pre><code>private class TestDeserializer implements JsonDeserializer&lt;Test&gt; { public Test deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); int id = obj.get("id").getAsInt(); String name = obj.get("name").getAsString(); double distance = obj.get("param_distance").getAsDouble(); int sampling = obj.get("param_sampling").getAsInt(); //assuming you have suitable constructors... Test test = new Test(id, name, new Parameters(distance, sampling)); return test; } } </code></pre> <p>Then you have to register the <code>TypeAdapter</code> with:</p> <pre><code>GsonBuilder gson = new GsonBuilder(); gson.registerTypeAdapter(Test.class, new TestDeserializer()); </code></pre> <p>And finally you just have to parse your JSON as usual, with:</p> <pre><code>gson.fromJson(yourJsonString, Test.class); </code></pre> <p>Gson will automatically use your custom deserializer to parse your JSON into your <code>Test</code> class.</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