I want to pass different List collection to 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 my class in different way Like these:
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 27 Json txt file in my assets folder and I want to parse these JSON txt file into their appropriate classes. How should I do that?
Editted: This way I catch an Exception:
Caused by: java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to com.mypackage.Form
I solved my 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With