How to use GSON's own TypeToken generic class?

I want to pass another List collection to the TypeToken class in GSON. Here is my class

public class ConvertToObject<T> { public T MappFrom(InputStream is) String json = ConvertJsonInputStream.toString(is); Gson gson = new Gson(); Type typeOfDest = new TypeToken<T>() { }.getRawType(); T lstObject = gson.fromJson(json, typeOfDest); return lstObject ; } } 

Now I want to instantiate the class in a different way. Here's how:

 AssetManager am = getApplicationContext().getAssets(); InputStream is = am.open("form.txt"); ConvertToObject<List<Form>> co = new ConvertToObject<List<Form>>(); List<Form> JsonForm = co.MappFrom(is); InputStream is2 = am.open("Messages.txt"); ConvertToObject<List<Messages>> co = new ConvertToObject<List<Messages>>(); List<Messages> JsonForm = co.MappFrom(is2); 

I have a 27 Json txt file in my resources folder and I want to parse this JSON txt file into the appropriate classes. How can I do it?

Editted: So I will catch the exception:

 Caused by: java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to com.mypackage.Form 
+8
json android gson
source share
1 answer

I solved the problem this way

 public class ConvertToObject<T> { public List<T> mapFrom(InputStream is, Type typeOfDest) { String json = ConvertJsonInputStream.toString(is); Gson gson = new Gson(); List<T> lstForm = gson.fromJson(json, typeOfDest); return lstForm; } 

And in my activity I have this code:

 ConvertToObject<Menu> co = new ConvertToObject<Menu>(); Type typeOfDest = new TypeToken<List<Menu>>() { }.getType(); AssetManager am = getResources().getAssets(); Log.i("AssetManager", "AssetManager"); InputStream is = null; try { is = am.open("menu.txt"); } catch (IOException e) { Log.i("InputStream", e.getMessage()); } List<Menu> JsonForm = co.mapFrom(is, typeOfDest); 
+9
source share

All Articles