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
打印出[{"itemValue":"1","itemLabel":"男"},{"itemValue":"2","itemLabel":"女"}]
(2)将上面的字符串转成List
String json = 上面的输出Gson gson = new Gson();List
报错如下:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.StringMap cannot be cast to
Option改成
Gson gson = new Gson();List
成功!
## pretty format
```java
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(newGroups);
```
参考:http://stackoverflow.com/questions/4226738/using-generics-with-gson