Gson processing generic

Source: Internet
Author: User

Parse json. I only like simple things. gson is relatively simple. I have been using it. Today I encountered a problem in processing generics.

The object classes used are as follows:

1
Class Option {
2
Public String itemValue;
3
Public String itemLabel;
4
 
5
Public Option (String itemValue, String itemLabel ){
6
This. itemValue = itemValue;
7
This. itemLabel = itemLabel;
8
}
9
}
(1) convert List to json string


1
List <Option> options = new ArrayList <Option> ();
2
Options. add (new Option ("1", "male "));
3
Options. add (new Option ("2", "female "));
4
Gson gson = new Gson ();
5
String json = gson. toJson (options, List. class );
6
System. out. println (json );

Print out [{"itemValue": "1", "itemLabel": "male" },{ "itemValue": "2", "itemLabel": "female"}]

(2) convert the above string to List

1
String json = output above
2
Gson gson = new Gson ();
3
List <Option> options = gson. fromJson (json, List. class );
4
For (Iterator it = options. iterator (); it. hasNext ();){
5
Option option = (Option) it. next ();
6
System. out. println (option. itemLabel );
7
}

The following error is reported:

Exception in thread "main" java. lang. ClassCastException: com. google. gson. internal. StringMap cannot be cast
Option

Change

1
Gson gson = new Gson ();
2
List <Option> options = gson. fromJson (json, new TypeToken <List <Option> () {}. getType ());
3
For (Iterator it = options. iterator (); it. hasNext ();){
4
Option option = (Option) it. next ();
5
System. out. println (option. itemLabel );
6
}
Successful!
 

 

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.