Deserializing Generic Types with GSON

前端 未结 5 2040
耶瑟儿~
耶瑟儿~ 2020-11-27 14:46

I have some problems with implementation of Json Deserialization in my Android application (with Gson library)

I\'ve made class like this

public clas         


        
5条回答
  •  春和景丽
    2020-11-27 15:15

    If you are using gson 2.8.0 or higher, you can use the following method TypeToken#getParametized((Type rawType, Type... typeArguments))

    Example:

    protected MyJson doInBackground(Class type, String json, Void... params) {
    
        GsonBuilder gson = new GsonBuilder();
        Type collectionType = TypeToken.getParameterized(MyJson.class, type).getType();
    
        MyJson myJson = gson.create().fromJson(json, collectionType);
    
        System.out.println(myJson.getPosts()); // [true, false]
        return myJson;
    }
    

    I believe this would work in your case.

    Credits to this answer.

提交回复
热议问题