Android's Gson-based Parameterizedtype for generic parsing

Source: Internet
Author: User

Create the Gsonresponsepasare parsing class,
classgsonresponsepasare<T> {
Tdeal(String response) {
Type Gsontype =Newtypetoken<commonresponse<T>> () {
}.gettype ();
commonresponse<T> commonresponse =NewGson (). Fromjson (response, Gsontype);
LG. E ("Data is:"+ Commonresponse.Data, "Class Type is:"+ Commonresponse.Data. GetClass (). toString ());
returnCommonresponse.Data;
}
}
Create a Commonresponse parsing entity and define the data data structure in generic form
commonresponse<T> {
Status ;
Data ;
}

1. Parsing basic data types
Gsonresponsepasare<string> (). Deal ("{\"status\ ": -4,\"  data\ ":\"xiaoxuan948\ "}");
LG. E (+ strresult);
The debug results are as follows

2. Parsing a custom object (failure process analysis) defines a definition for a derived object
Datainfo {
name ;
}

single Object parsing process
Datainfo Datainforesult =NewGsonresponsepasare<datainfo> (). Deal ("{\"Status\": -4,\"Data\":{\"name\":\"xiaoxuan948\"}}");
LG. E ("Datainfo:"+ datainforesult.tostring (), "Value:"+ Datainforesult.name);
The debug results are as follows
The analysis shows that the Commonresponse.data data type is not the desired datainfo type, but rather the linkedtreemap type, where a strong turn exception is indicated.
Collection Object parsing process
List<datainfo> resultlist =NewGsonresponsepasare<list<datainfo>> (). Deal ("{\"Status\": -4,\"Data\":[{\"name\":\"xiaoxuan948\"},{\"name\":\"Coca\"}]}");
for(Datainfo entity:resultlist) {
LG. E ("Datainfo:"+ entity.tostring (), "Value:"+ entity.name);
}
The debug results are as follows
Similar to parsing a single object, the data subset is of typeLinkedtreemap, not expected.The datainfo type.

Solution Solutions
classgsonresponsepasare<T>ImplementsParameterizedtype {
Private FinalUtilslogLG= Utilslog.GetLogger(Gsonresponsepasare.class);

PublicTdeal(String response) {
//Type Gsontype = new Parameterizedtype () {//...};//This method is not recommended, Gsonresponsepasare implementation Parameterizedtype is recommended. Because get Actualtypearguments here involves getting a generic collection of Gsonresponsepasare
Type Gsontype =This ;

commonresponse<T> commonresponse =NewGson (). Fromjson (response, Gsontype);
LG. E ("Data is:"+ Commonresponse.Data, "Class Type is:"+ Commonresponse.Data. GetClass (). toString ());
returnCommonresponse.Data;
}

@Override
PublicType[]getactualtypearguments() {
Class CLZ = This. GetClass ();
//You must pay attention to the use of new Gsonresponsepasare<gsonresponsepasare.datainfo> () {} Outside, and you must bring {} on the instantiation. Otherwise the acquired superclass is an object
Type superclass = Clz.getgenericsuperclass (); //getgenericsuperclass () gets the parent class with the generic type
if(SuperclassinstanceofClass) {
throw NewRuntimeException ("Missing type parameter.");
}
Parameterizedtype parameterized = (parameterizedtype) superclass;
returnParameterized.getactualtypearguments ();
}

@Override
PublicTypeGetownertype() {
return null;
}

@Override
PublicTypeGetrawtype() {
returnCommonresponse.class;
}
}
The calling code is as follows:
List<datainfo> resultlist =NewGsonresponsepasare<list<datainfo>> () {
}.deal ("{\"Status\": -4,\"Data\":[{\"name\":\"xiaoxuan948\"},{\"name\":\"Coca\"}]}");
for(Datainfo entity:resultlist) {
LG. E ("Datainfo:"+ entity.tostring (), "Value:"+ entity.name);
}

Gsonresponsepasare<datainfo> Pasare =NewGsonresponsepasare<datainfo> () {
};
Datainfo Datainforesult = Pasare.deal ("{\"Status\": -4,\"Data\":{\"name\":\"xiaoxuan948\"}}");
LG. E ("Datainfo:"+ datainforesult.tostring (), "Value:"+ Datainforesult.name);

Note:1. Direct AdoptionNew Gsonresponsepasare<gsonresponsepasare.datainfo> () {}; When parsing JSON data, be sure not to ignore the last {} section. 2.CommonResponse If it is an inner class, it must be declared as static type, otherwise it will prompt
Java.lang.IllegalArgumentException
At com.google.gson.internal. $Gson $preconditions.checkargument ($Gson $preconditions.java:$)
At com.google.gson.internal. $Gson $types$parameterizedtypeimpl.<init> ($Gson $types.java:448)
At com.google.gson.internal. $Gson $types.canonicalize ($Gson $types.java:103)
At Com.google.gson.reflect.typetoken.<init> (Typetoken.java:)
At Com.google.gson.reflect.TypeToken.get (Typetoken.java:296)
At Com.google.gson.Gson.fromJson (Gson.java:877)
At Com.google.gson.Gson.fromJson (Gson.java:844)
At Com.google.gson.Gson.fromJson (Gson.java:793) ...






From for notes (Wiz)

Android's Gson-based Parameterizedtype for generic parsing

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.