Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to deserialize JSON with GSON into corresponding generic Java types?
    primarykey
    data
    text
    <p>I want to deserialize a JSON object (using GSON, because I already use it for searializing objects) to a general Map of type <code>Map&lt;String, Object&gt;</code>. It should create Objects of types that do correspond to the according JSON types, i.e. this JSON Object</p> <pre><code>{ "docID" : "a12345", "relation" : ["1", "2", "3"], "title" : { "de" : "German Title", "en" : "English Title"} } </code></pre> <p>should be deserialized in a <code>Map&lt;String, Object&gt;</code> with entries of the following types:<br> (<code>String</code>, <code>String</code>), (<code>String</code>, <code>List&lt;String&gt;</code>), (<code>String</code>, <code>Map&lt;String, String&gt;</code>).</p> <p>I tried to use the following code:</p> <pre><code>class Dictionary_ extends HashMap&lt;String, Object&gt; { // nothing to do }; private static final GsonBuilder GSON_BUILDER = new GsonBuilder(); public Map&lt;String, Object&gt; deserializeJsonString(String jsonString) { Dictionary_ d = new Dictionary(); return GSON_BUILDER.create().fromJson(jsonString, d.getClass()); } </code></pre> <p>But then the resulting types of created Objects are as follows:<br> (<code>String</code>, <code>Object</code>), (<code>String</code>, <code>Object</code>), (<code>String</code>, <code>Object</code>) and I am not able to cast these objects into the corresponding "real" types, because I get class cast exceptions.</p> <p>I am not able to use POJOs, since the data I am receiving does not have predefined structure in terms of class members.</p> <p>So, how am I able to deserialize such generic data in according generic Java types?</p> <p><strong>Update:</strong><br> I just tried to implement it using JSON Simple, and it works out of the box very easily by the following code:</p> <pre><code> Object ret = JSONValue.parse(jsonString); return (List&lt;Map&lt;String, Object&gt;&gt;) ret; </code></pre> <p>Why does it not work that easy with GSON???</p>
    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