Gson项目地址:http://code.google.com/p/google-gson, 目前(2015-02-15)最新版本是gson-2.3.1.jar,
使用它可以轻松的将一个json字符串转换成对应的java对象. 和其它的同类产品相比, 他的优点在于你不需要使用注解标注目标对象, 你甚至无需知道目标对象的源代码. 另外gson在设计时充分考虑了对泛型的支持.
今天我就碰到了处理泛型时的问题
使用的实体类如下:
class Option {
public String itemValue;
public String itemLabel;
public Option(String itemValue, String itemLabel) {
this.itemValue = itemValue;
this.itemLabel = itemLabel;
}
}
(1)将List变成json字符串
List<Option> options = new ArrayList<Option>();
options.add(new Option("1", "男"));
options.add(new Option("2", "女"));
Gson gson = new Gson();
String json = gson.toJson(options, List.class);
System.out.println(json);
打印出[{"itemValue":"1","itemLabel":"男"},{"itemValue":"2","itemLabel":"女"}]
(2)将上面的字符串转成List
String json = 上面的输出
Gson gson = new Gson();
List<Option> options = gson.fromJson(json,List.class);
for (Iterator it = options.iterator(); it.hasNext();) {
Option option = (Option) it.next();
System.out.println(option.itemLabel);
}
报错如下:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to
Option
改成
Gson gson = new Gson();
List<Option> options = gson.fromJson(json,new TypeToken<List<Option>>(){}.getType());
for (Iterator it = options.iterator(); it.hasNext();) {
Option option = (Option) it.next();
System.out.println(option.itemLabel);
}
成功!
## pretty format
```java
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(newGroups);
```
参考:http://stackoverflow.com/questions/4226738/using-generics-with-gson