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!