KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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); }
Tags (comma-separated)
Save Edits
Cancel