使用GSON和泛型解析约定格式的JSON串(转)
时间紧张,先记一笔,后续优化与完善。
解决的问题:
使用GSON和泛型解析约定格式的JSON串。
背景介绍:
1.使用GSON来进行JSON串与java代码的互相转换。
2.JSON的格式如下三种:
#第一种:
{"success":true,"data":{"averageStarLevel":4.7,"remarkCount":10}}
#第二种:
{"success":true,"data":{"page":10,"pageCount":29,"list":[{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"}],"statistics":{"star5":20,"star4":40,"star3":30,"star2":10,"star1":0}}}
#第三种:{"success":true,"data":[{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"}]}
分析:
在工作时间中,遇到一种场景,就是在应用中调用多个JSON接口,各接口返回的数据内容不一样,如果逐一解析代码会比较臃肿。JSON串如上所列有三种基本格式。经过分析,发现三种JSON串有一个共同的特点。JSON结构一致:
{"success":true,"data":##}
success:代表是否访问成功
data:后面跟着所需信息.
基本相同的JSON结构,所以想定义一种通用模型对应到此结构。但是,data中的数据类型不一致。如第一种是简单对象,第二种是对象中嵌套数组,第三种是List。针对data数据类型不一致的情况,使用泛型来解决。
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import com.google.gson.Gson; public class CommonJson<T> implements Serializable { /**
*
*/
private static final long serialVersionUID = -3440061414071692254L; /**
* 是否成功
*/
private Boolean success; /**
* 数据
*/
private T data; public Boolean getSuccess() {
return success;
} public void setSuccess(Boolean success) {
this.success = success;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
}
}
GSON对于泛型的支持不足,为了使GSON对于泛型进行解析,JSON解析与组装代码如下:
public static CommonJson fromJson(String json, Class clazz) {
Gson gson = new Gson();
Type objectType = type(CommonJson.class, clazz);
return gson.fromJson(json, objectType);
} public String toJson(Class<T> clazz) {
Gson gson = new Gson();
Type objectType = type(CommonJson.class, clazz);
return gson.toJson(this, objectType);
} static ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
} public Type[] getActualTypeArguments() {
return args;
} public Type getOwnerType() {
return null;
}
};
}
以上两段代码可以满足第一种和第二种JSON的解析,对于第三种,data是List类型的,无法得到List<>的class,所以,针对第三种格式,实现代码如下:
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List; import com.google.gson.Gson; public class CommonJson4List<T> implements Serializable { /**
*
*/
private static final long serialVersionUID = -369558847578246550L; /**
* 是否成功
*/
private Boolean success; /**
* 数据
*/
private List<T> data; public Boolean getSuccess() {
return success;
} public void setSuccess(Boolean success) {
this.success = success;
} public List<T> getData() {
return data;
} public void setData(List<T> data) {
this.data = data;
} public static CommonJson4List fromJson(String json, Class clazz) {
Gson gson = new Gson();
Type objectType = type(CommonJson4List.class, clazz);
return gson.fromJson(json, objectType);
} public String toJson(Class<T> clazz) {
Gson gson = new Gson();
Type objectType = type(CommonJson4List.class, clazz);
return gson.toJson(this, objectType);
} static ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
} public Type[] getActualTypeArguments() {
return args;
} public Type getOwnerType() {
return null;
}
};
} }
测试代码如下:
import java.util.ArrayList;
import java.util.List; import com.alibaba.asc.sharewood.common.http.CommonJson;
import com.alibaba.asc.sharewood.common.http.CommonJson4List;
import com.alibaba.asc.sharewood.external.service.model.AverageStarLevelAndCount;
import com.alibaba.asc.sharewood.external.service.model.Evalution;
import com.alibaba.asc.sharewood.external.service.model.EvalutionProfile;
import com.alibaba.asc.sharewood.external.service.model.StarLevelStatistics; public class Test { @SuppressWarnings("unchecked")
public static void main(String[] args) { CommonJson<AverageStarLevelAndCount> cj = new CommonJson<AverageStarLevelAndCount>();
AverageStarLevelAndCount data = new AverageStarLevelAndCount();
data.setAverageStarLevel(4.7f);
data.setRemarkCount(10); cj.setSuccess(Boolean.TRUE);
cj.setData(data); String res1 = cj.toJson(AverageStarLevelAndCount.class); System.out.println(res1); CommonJson<AverageStarLevelAndCount> cj2 = CommonJson.fromJson(res1,
AverageStarLevelAndCount.class); System.out.println(cj2.getSuccess());
System.out.println(cj2.getData().getAverageStarLevel()); EvalutionProfile p = new EvalutionProfile();
p.setPage(10);
p.setPageCount(29); StarLevelStatistics s = new StarLevelStatistics();
s.setStar1(0);
s.setStar2(10);
s.setStar3(30);
s.setStar4(40);
s.setStar5(20); p.setStatistics(s); Evalution e1 = new Evalution(); e1.setStarLevel(4);
e1.setRemarkTime("2013-02-27 07:21:48");
e1.setRemarkCotnent("评价方未及时做出评价,系统默认满意!");
e1.setTpLogoURL("http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png");
e1.setExplainContent("");
e1.setPostMemberId("y**f"); Evalution e2 = new Evalution(); e2.setStarLevel(4);
e2.setRemarkTime("2013-02-27 07:21:48");
e2.setRemarkCotnent("评价方未及时做出评价,系统默认满意!");
e2.setTpLogoURL("http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png");
e2.setExplainContent("");
e2.setPostMemberId("y**f"); List<Evalution> le = new ArrayList<Evalution>();
le.add(e1);
le.add(e2); p.setList(le); CommonJson<EvalutionProfile> ce = new CommonJson<EvalutionProfile>(); ce.setSuccess(Boolean.TRUE);
ce.setData(p); String res2 = ce.toJson(EvalutionProfile.class); System.out.println(res2); String ps = "{\"data\":{\"pageCount\":29,\"page\":\"1\",\"list\":[{\"starLevel\":4,\"remarkTime\":\"2013-04-10 05:17:42\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**6\"},{\"starLevel\":4,\"remarkTime\":\"2013-04-05 04:42:40\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**8\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-20 00:52:18\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**5\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-07 01:51:01\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**7\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-06 03:38:57\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"z**2\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-06 03:17:33\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**2\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-03 01:40:17\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"a**6\"},{\"starLevel\":4,\"remarkTime\":\"2013-03-01 02:41:31\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"b**4\"},{\"starLevel\":4,\"remarkTime\":\"2013-02-28 03:20:45\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\",\"tpLogoURL\":\"\",\"explainContent\":\"\",\"postMemberId\":\"t**y\"},{\"starLevel\":4,\"remarkTime\":\"2013-02-27 07:21:48\",\"explainTime\":\"\",\"remarkContent\":\"评价方未及时做出评价,系统默认满意!\","
+ "\"tpLogoURL\":\""
+ "http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png\",\"explainContent\":\"\",\"postMemberId\":\"y**f\"}],"
+ "\"statistics\":{\"star5\":59,\"star4\":38,\"star3\":2,\"star2\":1,\"star1\":0}},\"success\":true}"; CommonJson<EvalutionProfile> re = CommonJson.fromJson(ps,
EvalutionProfile.class); System.out.println(re.getData().getStatistics().getStar5()); System.out.println(re.getData().getPageCount()); System.out.println(re.getData().getList().get(0).getPostMemberId()); CommonJson4List<Evalution> cjl = new CommonJson4List<Evalution>(); cjl.setSuccess(Boolean.TRUE);
cjl.setData(le); System.out.println("###" + cjl.toJson(Evalution.class)); String sList = "{\"data\":[{\"starLevel\":4,\"remarkCotnent\":\"评价方未及时做出评价,系统默认满意!\",\"remarkTime\":\"2013-02-27 07:21:48\",\"explainContent\":\"\",\"postMemberId\":\"y**f\",\"tpLogoURL\":\"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png\"},{\"starLevel\":4,\"remarkCotnent\":\"评价方未及时做出评价,系统默认满意!\",\"remarkTime\":\"2013-02-27 07:21:48\",\"explainContent\":\"\",\"postMemberId\":\"y**f\",\"tpLogoURL\":\"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png\"}],\"success\":true}"; CommonJson4List<Evalution> cjle = CommonJson4List.fromJson(sList,
Evalution.class); System.out.println("***"
+ cjle.getData().get(0).getPostMemberId()); }
}
执行结果如下:
{"success":true,"data":{"averageStarLevel":4.7,"remarkCount":10}}
true
4.7
{"success":true,"data":{"page":10,"pageCount":29,"list":[{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"}],"statistics":{"star5":20,"star4":40,"star3":30,"star2":10,"star1":0}}}
59
29
b**6
{"success":true,"data":[{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"},{"starLevel":4,"remarkCotnent":"评价方未及时做出评价,系统默认满意!","remarkTime":"2013-02-27 07:21:48","explainContent":"","postMemberId":"y**f","tpLogoURL":"http://i04.c.aliimg.com/cms/upload/2012/186/684/486681_1232736939.png"}]}
y**f
Ps:文中说到Gson对泛型的支持不足,其实是不正确的,Gson对泛型做了以下支持:
public static CommonJson4List fromJson(String json, Class clazz) {
Gson gson = new Gson();
Type objectType = new TypeToken<CommonJson4List<clazz>>() {}.getType();
return gson.fromJson(json, objectType);
}
只需将获取类型的泛型类作为TypeToken的泛型参数构造一个匿名的子类,就可以通过getType方法获取一个parameterized类型,结果与type方法一致。
使用GSON和泛型解析约定格式的JSON串(转)的更多相关文章
- 菜鸟学习Spring——SpringMVC注解版解析不同格式的JSON串
一.概述 不同格式的JSON串传到后台来实现功能这个是我们经常要做的一件事,本篇博客就给大家介绍四种不同的JSON串传到后台后台如何用@RequestBody解析这些不同格式的JSON串的. 二.代码 ...
- Android 解析未知格式的json数据
1.递归一有的时候我们需要解析未知的json.或者说是动态的json.那么我们并不知道key具体是多少,或者说key不是固定的.这时候就需要解析动态key的方法. 这个方法是我在实现解析前台传入的js ...
- Gson解析list类型的json串
Gson gson = new Gson(); Type type = new TypeToken<List<Object>>() {}.getType(); List< ...
- new JSONObject(str)无法解析 报错:org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject 解析服务器返回的Jso ...
- GSON转换日期数据为特定的JSON数据
通过JSON传递数据的时候经常需要传递日期,Java中可以通过GSON将日期转换为特定格式的JSON数据. 1.普通的GSON转换日期 public void query(HttpServletReq ...
- python中文json串创建与解析
下面代码,举例说明了json如何创建和解析含有中文的json串: #coding=gbk import os import sys reload(sys) sys.setdefaultencoding ...
- SpringMVC Jackson 库解析 json 串属性名大小写自动转换问题
问题描述 在项目开发中,当实体类和表中定义的某个字段为 RMBPrice,首字母是大写的,sql 查询出来的列名也是大写的 RMBPrice,但是使用 jquery 的 ajax 返回请求响应时却出错 ...
- Reflection和Expression Tree解析泛型集合快速定制特殊格式的Json
很多项目都会用到Json,而且大部分的Json都是格式固定,功能强大,转换简单等,标准的key,value集合字符串:直接JsonConvert.SerializeObject(List<T&g ...
- Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson
Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson等等 本人fastJson用了两年,也是从去年才开始接触Gson,希望下面的总结会对博友有用,至于Gso ...
随机推荐
- HttpClient与HttpUrlConnection下载速度比较
Android有两套http的API,刚开始使用网络编程时多少有些迷惑到底用哪个好呢?其实孰优孰劣无需再争论,google已经指出HttpUrlConnection是Android更优的选择,并在SD ...
- win8开wifi共享无法使用的问题解决办法
相信现在不少人都安装了windows8操作系统,因为windows8这个全新的操作系统用起来 确实挺强大,包括漂亮的开始屏,但是不得不说这个系统的兼容性还是有待提高,所以win8我的 装了又卸,卸了又 ...
- 记关于webpack4下css提取打包去重复的那些事
注意使用vue-cli3(webpack4),默认小于30k不会抽取为公共文件,包括css和js,已测试 经过2天的填坑,现在终于有点成果 环境webpack4.6 + html-webpack-pl ...
- 面积并+扫描线 覆盖的面积 HDU - 1255
题目链接:https://cn.vjudge.net/problem/HDU-1255 题目大意:中文题目 具体思路:和上一篇的博客思路差不多,上一个题求的是面积,然后我们这个地方求的是啊覆盖两次及两 ...
- UART中的硬件流控RTS与CTS【转】
转自:http://blog.csdn.net/zeroboundary/article/details/8966586 5/23/2013 5:13:04 PM at rock-chips insh ...
- linux根据端口查找进程【原创】
如转载请注明地址 1.利用lsof -i:端口号 lsof -i:端口号 [root@01 ~]# lsof -i:8097COMMAND PID USER FD TYPE DEVICE SIZE/O ...
- Linux系统产生随机数/dev/random 和 /dev/urandom
1. 基本介绍 /dev/random和/dev/urandom是Linux系统中提供的随机伪设备,这两个设备的任务,是提供永不为空的随机字节数据流.很多解密程序与安全应用程序(如SSH Keys, ...
- mysql 用init-connect+binlog实现用户操作追踪做access的ip的log记录
在MYSQL中,每个连接都会先执行init-connect,进行连接的初始化.我们可以在这里获取用户的登录名称和thread的ID值.然后配合binlog,就可以追踪到每个操作语句的操作时间,操作人等 ...
- LeetCode(13):罗马数字转整数
Easy! 题目描述: 罗马数字包含以下七种字符:I, V, X, L,C,D 和 M. 字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000 例如, 罗马数字 2 写 ...
- CF1064A 【Make a triangle!】
要让这个三角形合法,只需满足三角形不等式 即$a+b>c$,设$c=max\left\{a,b,c\right\}$,上式转化为$c<a+b$ 如果已经满足,不需消耗代价 否则消耗$c-a ...