Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a generic type with Gson

I am trying to create a generic class for use with Google Gson. I've created the class GsonJsonConverterImplementation<T>. This class has the following method:

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 } 

The goal is that this method should be able to work with whatever Type I have set my GsonJsonConverterImplementation to work with. Unfortunately, gson.fromJson(jsonString, T) does not work, nor does using T.class 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?

Edit
Using Kris's answer 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?

public List<T> deserializeList(String jsonString, Class<T> clazz) {     GsonBuilder builder = new GsonBuilder();     builder.setDateFormat("MM/dd/yy HH:mm:ss");     Gson gson = builder.create();      Type listType = new TypeToken<clazz>(){}.getType(); // compiler error      return gson.fromJson(jsonString, listType); } 
like image 705
ahsteele Avatar asked Mar 20 '11 19:03

ahsteele


1 Answers

The simplest approach for what you are attempting is to define the type of class which is to be returned in the method signature itself. You can do so by either passing an instance of 'T' to the method or the Class of the value to be returned. The second approach is the more typical in cases where you expect to generate a return value. Here is an example of this approach using Gson:

public <T> T deserialize(String jsonString, Class<T> clazz) {     GsonBuilder builder = new GsonBuilder();     builder.setDateFormat("MM/dd/yy HH:mm:ss");      Gson gson = builder.create();     return gson.fromJson(jsonString, clazz); } 

Usage:

MyClass mc = deserialize(jsonString, MyClass.class); 
like image 187
Kris Babic Avatar answered Oct 14 '22 11:10

Kris Babic