博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
gson 处理泛型
阅读量:7102 次
发布时间:2019-06-28

本文共 1561 字,大约阅读时间需要 5 分钟。

hot3.png

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

 

 

转载于:https://my.oschina.net/uniquejava/blog/87449

你可能感兴趣的文章
雪城大学信息安全讲义 4.3~4.4
查看>>
JSP的客户端请求
查看>>
Memcached启动提示:cann't run as root without the -u switch
查看>>
300+参展品牌,10+同期会议,IOTE2018国际物联网展苏州开幕
查看>>
New Product Launch: Alibaba Cloud Data Integration
查看>>
人工智能玩具安全性遭质疑,刺痛了谁的神经?
查看>>
Mac系统下利用ADB命令连接android手机并进行文件操作
查看>>
修改Windows和linux系统时间
查看>>
深入VR教育乱象,教育部和工信部召开研讨会
查看>>
深入分析Spring 与 Spring MVC容器
查看>>
在已有元素后面插入一个新元素,属于通用型函数insertAfter(newElement,targetElement)...
查看>>
lesson6-表
查看>>
来自二维世界的忧愁:如何避免康康的悲剧再次重演?
查看>>
传教士与野人过河问题
查看>>
.NET Framework 3.5 Common Namespaces and Types Poster
查看>>
Winform应用程序实现通用遮罩层
查看>>
python+uwsgi导致redis无法长链接引起性能下降问题记录
查看>>
对linux安全设置中需要注意和掌握的地方
查看>>
HDFS-Architecture剖析
查看>>
百花齐放,繁荣和瓶颈同在,2016年VR AR产业梳理
查看>>