Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a generic type with Gson
    primarykey
    data
    text
    <p>I am trying to create a generic class for use with <a href="http://code.google.com/p/google-gson/" rel="nofollow noreferrer">Google Gson</a>. I've created the class <code>GsonJsonConverterImplementation&lt;T&gt;</code>. This class has the following method:</p> <pre><code>public T deserialize(String jsonString) { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("MM/dd/yy HH:mm:ss"); Gson gson = builder.create(); return gson.fromJson(jsonString, T); // T.class etc. what goes here } </code></pre> <p>The goal is that this method should be able to work with whatever Type I have set my GsonJsonConverterImplementation to work with. Unfortunately, <code>gson.fromJson(jsonString, T)</code> does not work, nor does using <code>T.class</code> in place of T. I am sure the issue stems from my lack of understanding of Java generic types. What is the correct way of using a generic with Gson?</p> <p><strong>Edit</strong><br /> Using <a href="https://stackoverflow.com/questions/5370768/using-a-generic-type-with-gson/5370998#5370998">Kris's answer</a> I would assume that this should work. Unfortunately, clazz cannot be used in this manner and causes a compiler error. What are my options for working with a collection and a generic type with Gson?</p> <pre><code>public List&lt;T&gt; deserializeList(String jsonString, Class&lt;T&gt; clazz) { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("MM/dd/yy HH:mm:ss"); Gson gson = builder.create(); Type listType = new TypeToken&lt;clazz&gt;(){}.getType(); // compiler error return gson.fromJson(jsonString, listType); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    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