gson 处理泛型
解析json, 我只喜欢简单的东西,gson比较简单,我一直用它,今天碰到了处理泛型时的问题
使用的实体类如下:
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)将List变成json字符串
1
List<Option> options = new ArrayList<Option>();
2
options.add(new Option("1", "男"));
3
options.add(new Option("2", "女"));
4
Gson gson = new Gson();
5
String json = gson.toJson(options, List.class);
6
System.out.println(json);
打印出[{"itemValue":"1","itemLabel":"男"},{"itemValue":"2","itemLabel":"女"}]
(2)将上面的字符串转成List
1
String json = 上面的输出
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
}
报错如下:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to
Option
改成
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
}
成功!
补充:web前端 , JavaScript ,