Note that there are some explanatory texts on larger screens.

plurals
  1. POGSON parsing unspecified type variable
    primarykey
    data
    text
    <p>I parse server JSON response with GSON library. Backend guys sometimes tell me: "We can't specify variable type in JSON for some reason" (old php, they don't know how to do it and so on and so forth). GSON likes strong typing in its object model. So I can't parse Object as String.</p> <p>GSON wait for:</p> <pre><code>{ "service":{ "description":null, "name":"Base", "id":"4c7a90410529" } } </code></pre> <p>But it gets (empty data):</p> <pre><code>"service": "" </code></pre> <p>And I get</p> <pre><code>java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1396 </code></pre> <p>What is the best practice to parse such response?</p> <p>Another question: How can I build object, it can recognize Integer variable which returned from time to time as Integer or as String? The same server side issue.</p> <pre><code>"data": "1" </code></pre> <p>or</p> <pre><code>"data": 1 </code></pre> <p>I know - we should use specific types in Java. But sometime it is worth to make concessions, <br>Thanks</p> <p><strong>EDIT:</strong> My solution based on Java Developer's answer. <br>ServiceDeserializer class deserialize every object depending on its internal value.</p> <pre><code>public class ServiceDeserializer implements JsonDeserializer&lt;ServiceState&gt;{ @Override public ServiceState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String name = ""; String uuid = ""; String description = ""; if (json.isJsonObject()) { JsonObject obj = json.getAsJsonObject(); if (!obj.get("name").isJsonNull()) { name = obj.get("name").getAsString(); } if (!obj.get("uuid").isJsonNull()) { uuid = obj.get("uuid").getAsString(); } if (!obj.get("description").isJsonNull()) { description = obj.get("description").getAsString(); } } return new ServiceState(name, uuid, description); } } </code></pre> <p>And my GSON constructor with type adapter for ServiceState.</p> <pre><code>Gson gson = new GsonBuilder() .registerTypeAdapter(ServiceState.class, new ServiceDeserializer()) .create(); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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