Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom generic in GSON TypeToken class?

Tags:

json

android

gson

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
like image 629
Misagh Aghakhani Avatar asked Dec 02 '12 11:12

Misagh Aghakhani


1 Answers

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);
like image 88
Misagh Aghakhani Avatar answered Sep 29 '22 03:09

Misagh Aghakhani