Android Development: How to handle generics with Gson

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.