Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From <a href="http://wiki.fasterxml.com/JacksonInFiveMinutes" rel="nofollow">http://wiki.fasterxml.com/JacksonInFiveMinutes</a> (but also look at TypeFactory in Jackson 1.3+) : </p> <blockquote> <p><strong>Data Binding with Generics</strong></p> </blockquote> <p>In addition to binding to POJOs and "simple" types, there is one additional variant: that of binding to generic (typed) containers. This case requires special handling due to so-called Type Erasure (used by Java to implement generics in somewhat backwards compatible way), which prevents you from using something like Collection.class (which does not compile).</p> <p>So if you want to bind data into a Map you will need to use:</p> <pre><code> Map&lt;String,User&gt; result = mapper.readValue(src, new TypeReference&lt;Map&lt;String,User&gt;&gt;() { }); </code></pre> <p>where TypeReference is only needed to pass generic type definition (via anynomous inner class in this case): the important part is > which defines type to bind to.</p> <p>If you don't do this (and just pass Map.class), call is equivalent to binding to Map (i.e. "untyped" Map), as explained above.</p> <hr> <p>If you mean polymorphic deserialization, check this link <a href="http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html" rel="nofollow">http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html</a> which discusses using the jackson annotations to assist the mapper in picking the right object for the job.</p> <hr> <p>I wrote this today (I'm sure it can be improved) for simply taking a JSON string and always converting it into a List of DTOs (or whatever it can be converted into). This could be called with any type, and could be modified to return a single instance, or List, or whatever you wished. OBJECT_MAPPER is a static ObjectMapper variable.</p> <pre><code> public static &lt;T&gt; List&lt;T&gt; getFromJSONCollection(String jsonString, final Class&lt;T&gt; type) throws IOException { try { return OBJECT_MAPPER.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, type)); } catch (JsonMappingException e) { return getFromJSON(jsonString, type); } } public static &lt;T&gt; List&lt;T&gt; getFromJSON(final String jsonString, final Class&lt;T&gt; type) throws IOException { return new ArrayList&lt;T&gt;() {{ add(OBJECT_MAPPER.readValue(jsonString, type));}}; } </code></pre>
 

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