Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Assuming that the different possible JSON requests you may have are not extremely different to each other, I suggest a different approach, simpler in my opinion.</p> <p>Let's say that you have these 3 different JSON requests:</p> <pre><code>{ "type":"LOGIN", "username":"someuser", "password":"somepass" } //////////////////////////////// { "type":"SOMEREQUEST", "param1":"someValue", "param2":"someValue" } //////////////////////////////// { "type":"OTHERREQUEST", "param3":"someValue" } </code></pre> <p>Gson allows you to have a single class to <em>wrap</em> all the possible responses, like this:</p> <pre><code>public class Request { @SerializedName("type") private String type; @SerializedName("username") private String username; @SerializedName("password") private String password; @SerializedName("param1") private String param1; @SerializedName("param2") private String param2; @SerializedName("param3") private String param3; //getters &amp; setters } </code></pre> <p>By using the annotation <code>@SerializedName</code>, when Gson try to parse the JSON request, it just look, for each named attribute in the class, if there's a field in the JSON request with the same name. If there's no such field, the attribute in the class is just set to <code>null</code>. </p> <p>This way you can parse many different JSON responses using only your <code>Request</code> class, like this:</p> <pre><code>Gson gson = new Gson(); Request request = gson.fromJson(jsonString, Request.class); </code></pre> <p>Once you have your JSON request parsed into your class, you can transfer the data from the <em>wrap</em> class to a concrete <code>XxxxRequest</code> object, something like:</p> <pre><code>switch (request.getType()) { case "LOGIN": LoginRequest req = new LoginRequest(request.getUsername(), request.getPassword()); break; case "SOMEREQUEST": SomeRequest req = new SomeRequest(request.getParam1(), request.getParam2()); break; case "OTHERREQUEST": OtherRequest req = new OtherRequest(request.getParam3()); break; } </code></pre> <p>Note that this approach gets a bit more tedious if you have many different JSON requests and those requests are very different to each other, but even so I think is a good and very simple approach...</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