In the actual development, often with Gson processing interface returned data, because of the type of processing, need to write different methods, also because the return is an object or list, but also to write different methods, this does not conform to the development and development of the reuse principle, the code as far as possible to reuse, I found a reusable method, directly into the data to be parsed and return the type of object, directly out of the parse result, once and for all, the specific method is as follows:
Protected <T> T Getgsonobject (String data, class<t> mclass) {T result = Gson.fromjson (data, mclass); return res Ult;} Public <T> list<t> getgsonlist (String data, class<t> Klass) { return Gson.fromjson (data, new Listofsomething<t> (Klass));} Class Listofsomething<x> implements Parameterizedtype { private class<?> wrapped; Public listofsomething (class<x> wrapped) { this.wrapped = wrapped; } Public type[] Getactualtypearguments () { return new type[] {wrapped}; } Public Type Getrawtype () { return list.class; } Public Type Getownertype () { return null; }}
The two methods above are simply passing in the string that needs to be parsed and the class type returned, directly getting the result we need, when it saves a lot of time
This article refers to a lot of stackoverflow above the material, as translation it.
Android Development: How to handle generics with Gson