Deserializing Generic Types with GSON

前端 未结 5 2046
耶瑟儿~
耶瑟儿~ 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 14:54

    You have to specify the type of T at the time of deserialization. How would your List of posts get created if Gson didn't know what Type to instantiate? It can't stay T forever. So, you would provide the type T as a Class parameter.

    Now assuming, the type of posts was String you would deserialize MyJson as (I've also added a String json parameter for simplicity; you would read from your reader as before):

    doInBackground(String.class, "{posts: [\"article 1\", \"article 2\"]}");
    
    protected MyJson doInBackground(Class type, String json, Void... params) {
    
        GsonBuilder gson = new GsonBuilder();
        Type collectionType = new TypeToken>(){}.getType();
    
        MyJson myJson = gson.create().fromJson(json, collectionType);
    
        System.out.println(myJson.getPosts()); // ["article 1", "article 2"]
        return myJson;
    }
    

    Similarly, to deserialize a MyJson of Boolean objects

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

    I've assumed MyJson for my examples to be as

    public class MyJson {
    
        public List posts;
    
        public List getPosts() {
            return posts;
        }
    }
    

    So, if you were looking for to deserialize a List you would invoke the method as

    // assuming no Void parameters were required
    MyJson myJson = doInBackground(MyObject.class);
    

提交回复
热议问题