Deserializing Generic Types with GSON

前端 未结 5 2047
耶瑟儿~
耶瑟儿~ 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:06

    So the above answer didn't work for me, after trial and error that's how my code ended:

    public class AbstractListResponse {
        private List result;
    
        public List getResult() {
            return this.result;
        }
    }
    

    The important part here is the method signature, including the '< T >' on the left.

    protected  AbstractListResponse parseAbstractResponse(String json, TypeToken type) {
        return new GsonBuilder()
                .create()
                .fromJson(json, type.getType());
    }
    

    When calling Gson, the method receives the TypeToken of the generic object.

    TypeToken> typeToken = new TypeToken>() {};
    AbstractListResponse responseBase = parseAbstractResponse(json, typeToken);
    

    And finally the TypeToken can use MyDTO, or even a simple object, just MyDTO.

提交回复
热议问题