JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript 规范的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
基本写一个涉及网络请求数据的App都要去解析Json数据。xml方式效率不如Json来的高,所以首选还是Json。本文将分别进行原生技术手动解析、使用Gson和FastJson三种方法来解析Json数据。
Gson是Google提供的一种解析json数据的框架,编码简洁,官方推荐。Fastjson是一个Java语言编写的高性能功能完善的JSON库,它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。
很简单,遇到{…}就是Json对象,遇到[…]就是Json数组。
无论是Json数组还是Json对象,都是字符串,均可以转成JavaBean或者JavaBean的List集合。
原生技术手动解析
将json对象转换成JavaBean
Api介绍(org.json包下)
JSONObject(String string) : 构造函数,将json字符串解析为json对象.
int length() : 得到json对象的长度.
Xxx getXxx(String name) : 根据name获取json对象中对应的value,不存在时造成空指针异常.
Xxx optXxx(String name) : 根据name获取json对象中对应的value,不存在时返回""或默认值.
测试json数据
{
"status": "0",
"msg": "ok",
"result": "哈哈啊哈哈哈哈"
}
实现解析
private void jsonToJavaBeanByNative() {
String json = "{\n" +
" \"status\": \"0\",\n" +
" \"msg\": \"ok\",\n" +
" \"result\": \"哈哈啊哈哈哈哈\"\n" +
"}";
//解析
try {
JSONObject jsonObject = new JSONObject(json);
String status = jsonObject.getString("status");
String result = jsonObject.optString("result");
String msg = jsonObject.optString("msg");
tv1.setText(json);
tv2.setText(new DemoBean(status, msg, result).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
将json数组转换成JavaBean的List集合
Api介绍(org.json包下)
JSONArray(String string) : 构造函数,将json字符串解析为json数组.
int length() : 得到json数组的长度.
Xxx getXxx(String name) : 根据name获取json数组中对应的value,不存在时造成空指针异常.
Xxx optXxx(String name) : 根据name获取json数组中对应的value,不存在时返回""或默认值.
测试json数据
[
{
"status": "0",
"msg": "ok",
"result": "哈哈啊哈哈哈哈"
},
{
"status": "1",
"msg": "Error",
"result": "空的"
}
]
实现解析
private void jsonToJavaBeanListByNative() {
String json = "[\n" +
" {\n" +
" \"status\": \"0\",\n" +
" \"msg\": \"ok\",\n" +
" \"result\": \"哈哈啊哈哈哈哈\"\n" +
" },\n" +
" {\n" +
" \"status\": \"1\",\n" +
" \"msg\": \"Error\",\n" +
" \"result\": \"空的\"\n" +
" }\n" +
"]";
List list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
if(obj != null){
String status = obj.getString("status");
String result = obj.optString("result");
String msg = obj.optString("msg");
list.add(new DemoBean(status, msg, result));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
tv1.setText(json);
tv2.setText(list.toString());
}
复杂json数据解析
测试json数据
{
"status": "0",
"msg": "ok",
"result": {
"total": "33731",
"pagenum": "1",
"pagesize": "1",
"list": [
{
"content": "文化交流请问如何气温哦日哦还欠我I偶然穷温家穷文件哦I你去我就饿哦老婆群文件欧赔",
"addtime": "2014-10-14 15:48:18",
"url": "http://m.kaixinhui.com/detail-26458.html"
},
{
"content": "可是到了好看你看我哪舍得回来可完全认可啊你说的卡就好了啊深刻的理解好看啦可能去问价钱",
"addtime": "2014-10-14 15:48:18",
"url": "http://m.kaixinhui.com/detail-26458.html"
}
]
}
}
实现解析
private void parseComplexJson() {
String json = "{\n" +
" \"status\": \"0\",\n" +
" \"msg\": \"ok\",\n" +
" \"result\": {\n" +
" \"total\": \"33731\",\n" +
" \"pagenum\": \"1\",\n" +
" \"pagesize\": \"1\",\n" +
" \"list\": [\n" +
" {\n" +
" \"content\": \"文化交流请问如何气温哦日哦还欠我I偶然穷温家穷文件哦I你去我就饿哦老婆群文件欧赔\",\n" +
" \"addtime\": \"2014-10-14 15:48:18\",\n" +
" \"url\": \"http://m.kaixinhui.com/detail-26458.html\"\n" +
" },\n" +
" {\n" +
" \"content\": \"可是到了好看你看我哪舍得回来可完全认可啊你说的卡就好了啊深刻的理解好看啦可能去问价钱\",\n" +
" \"addtime\": \"2014-10-14 15:48:18\",\n" +
" \"url\": \"http://m.kaixinhui.com/detail-26458.html\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
ComplexDemoBean complexDemoBean = new ComplexDemoBean();
try {
JSONObject jsonObject = new JSONObject(json);
complexDemoBean.setStatus(jsonObject.optString("status"));
complexDemoBean.setMsg(jsonObject.optString("msg"));
JSONObject object = jsonObject.optJSONObject("result");
ComplexDemoBean.ResultBean resultBean = new ComplexDemoBean.ResultBean();
resultBean.setTotal(object.optString("total"));
resultBean.setPagenum(object.optString("pagenum"));
resultBean.setPagesize(object.optString("pagesize"));
JSONArray list = object.getJSONArray("list");
List beanList = new ArrayList<>();
for (int i = 0; i < list.length(); i++){
ComplexDemoBean.ResultBean.ListBean listBean = new ComplexDemoBean.ResultBean.ListBean();
JSONObject obj = list.getJSONObject(i);
listBean.setContent(obj.optString("content"));
listBean.setAddtime(obj.optString("addtime"));
listBean.setUrl(obj.optString("url"));
beanList.add(listBean);
}
resultBean.setList(beanList);
complexDemoBean.setResult(resultBean);
tv1.setText(json);
tv2.setText(complexDemoBean.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
特殊json数据解析
有些数据他们的key为数字,使用GsonFormat插件生成JavaBean是有问题的,这时需要我们自己去手写Bean。
示例Json
{
"code": 0,
"list": {
"0": {
"aid": "9698756",
"author": "哔哩哔哩番剧",
"copyright": "Copy",
"create": "2017-04-08 18:39",
"coins": 22043
},
"1": {
"aid": "9854952",
"author": "哔哩哔哩番剧",
"copyright": "Copy",
"create": "2017-04-15 15:29",
"coins": 16991
}
}
}
自定义JavaBean
public class FilmInfo {
private int code;
private List list;
@Override
public String toString() {
return "FilmInfo{" +
"code=" + code +
", list=" + list +
'}';
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public static class FilmBean{
private String aid;
private String author;
private int coins;
private String copyright;
private String create;
@Override
public String toString() {
return "FilmBean{" +
"aid='" + aid + '\'' +
", author='" + author + '\'' +
", coins=" + coins +
", copyright='" + copyright + '\'' +
", create='" + create + '\'' +
'}';
}
public String getAid() {
return aid;
}
public void setAid(String aid) {
this.aid = aid;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getCoins() {
return coins;
}
public void setCoins(int coins) {
this.coins = coins;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCreate() {
return create;
}
public void setCreate(String create) {
this.create = create;
}
}
}
实现解析
private void specialJsonParse() {
String json = "{\n" +
" \"code\": 0,\n" +
" \"list\": {\n" +
" \"0\": {\n" +
" \"aid\": \"9698756\",\n" +
" \"author\": \"哔哩哔哩番剧\",\n" +
" \"copyright\": \"Copy\",\n" +
" \"create\": \"2017-04-08 18:39\",\n" +
" \"coins\": 22043\n" +
" },\n" +
" \"1\": {\n" +
" \"aid\": \"9854952\",\n" +
" \"author\": \"哔哩哔哩番剧\",\n" +
" \"copyright\": \"Copy\",\n" +
" \"create\": \"2017-04-15 15:29\",\n" +
" \"coins\": 16991\n" +
" }\n" +
" }\n" +
"}";
FilmInfo filmInfo = new FilmInfo();
try {
JSONObject jsonObject = new JSONObject(json);
filmInfo.setCode(jsonObject.optInt("code"));
List list = new ArrayList<>();
JSONObject object = jsonObject.optJSONObject("list");
for(int i = 0; i < object.length(); i++){
FilmInfo.FilmBean filmBean = new FilmInfo.FilmBean();
filmBean.setAid(object.getJSONObject(i+"").getString("aid"));
filmBean.setAuthor(object.getJSONObject(i+"").getString("author"));
filmBean.setCopyright(object.getJSONObject(i+"").getString("copyright"));
filmBean.setCreate(object.getJSONObject(i+"").getString("create"));
filmBean.setCoins(object.getJSONObject(i+"").getInt("coins"));
list.add(filmBean);
}
filmInfo.setList(list);
tv1.setText(json);
tv2.setText(filmInfo.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
Gson框架解析
将json对象字符串转换为javaBean
Api介绍(compile ‘com.google.code.gson:gson:2.8.0’)
fromJson(String json, Class classOfT); //要求json对象中的key的名称与java对象对应的类中的属性名要相同
json数据示例
{
"id":2, "name":"大虾",
"price":12.3,
"imagePath":"http://192.168.10.165:8080/L05_Server/images/f1.jpg"
}
实现解析
private void jsonToJavaBeanByGson() {
String json = "{\n" +
"\t\"id\":2, \"name\":\"大虾\", \n" +
"\t\"price\":12.3, \n" +
"\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
"}\n";
Gson gson = new Gson();
ShopBean shopBean = gson.fromJson(json, ShopBean.class);
tv1.setText(json);
tv2.setText(shopBean.toString());
}
将json数组字符串转换成javaBean的List集合
Api介绍
fromJson(String json, Type typeOfT);
//第二个参数传递Type类型 e.g. new TypeToken>(){}.getType()
json数据示例
[
{
"id": 1,
"imagePath": "http://192.168.10.165:8080/f1.jpg",
"name": "大虾1",
"price": 12.3
},
{
"id": 2,
"imagePath": "http://192.168.10.165:8080/f2.jpg",
"name": "大虾2",
"price": 12.5
}
]
实现解析
private void jsonToJavaBeanListByGson() {
String json = "[\n" +
" {\n" +
" \"id\": 1,\n" +
" \"imagePath\": \"http://192.168.10.165:8080/f1.jpg\",\n" +
" \"name\": \"大虾1\",\n" +
" \"price\": 12.3\n" +
" },\n" +
" {\n" +
" \"id\": 2,\n" +
" \"imagePath\": \"http://192.168.10.165:8080/f2.jpg\",\n" +
" \"name\": \"大虾2\",\n" +
" \"price\": 12.5\n" +
" }\n" +
"]";
Gson gson = new Gson();
List list = gson.fromJson(json, new TypeToken>(){}.getType());
tv1.setText(json);
tv2.setText(list.toString());
}
将java对象转换为json字符串
Api介绍
String toJson(Object src);
实现转换
private void javaBeanToJsonByGson() {
DemoBean demoBean = new DemoBean("0", "haha", "是你答复我还是额咯结尾");
Gson gson = new Gson();
String json = gson.toJson(demoBean);
tv1.setText(demoBean.toString());
tv2.setText(json);
}
将javaBean的集合对象转换成json数组
Api介绍
String toJson(Object src);
实现转换
private void javaBeanListToJsonByGson() {
List list = new ArrayList<>();
ShopBean shopBean1 = new ShopBean("http://www.baidu.com", 12.3, "鱼肉", 1);
ShopBean shopBean2 = new ShopBean("http://www.baidu.com", 15.7, "鸡腿", 2);
list.add(shopBean1);
list.add(shopBean2);
Gson gson = new Gson();
String json = gson.toJson(list);
tv1.setText(list.toString());
tv2.setText(json);
}
FastJson框架解析
将json对象字符串转换为javaBean
Api介绍(compile ‘com.alibaba:fastjson:1.2.31’)
Json.parseObject(String json, Class classOfT);
实现解析
private void javaBeanListToJsonByFastJson() {
String json = "{\n" +
"\t\"id\":2, \"name\":\"大虾\", \n" +
"\t\"price\":12.3, \n" +
"\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
"}\n";
ShopBean shopBean = JSON.parseObject(json, ShopBean.class);
tv1.setText(json);
tv2.setText(shopBean.toString());
}
将json数组字符串转换成javaBean的List集合
Api介绍
Json.List parseArray(String json,Class classOfT);
实现解析
private void javaBeanListToJsonByFastJson() {
String json = "{\n" +
"\t\"id\":2, \"name\":\"大虾\", \n" +
"\t\"price\":12.3, \n" +
"\t\"imagePath\":\"http://192.168.10.165:8080/L05_Server/images/f1.jpg\"\n" +
"}\n";
ShopBean shopBean = JSON.parseObject(json, ShopBean.class);
tv1.setText(json);
tv2.setText(shopBean.toString());
}
将java对象转换为json字符串
Api介绍
String Json.toJSONString(Object object);
实现解析
private void javaBeanToJsonByFastJson() {
DemoBean demoBean = new DemoBean("0", "haha", "是你答复我还是额咯结尾");
String jsonString = JSON.toJSONString(demoBean);
tv1.setText(demoBean.toString());
tv2.setText(jsonString);
}
将javaBean的集合对象转换成json数组
Api介绍
String Json.toJSONString(Object object);
实现解析
private void javaBeanListToJsonByFastJson() {
List list = new ArrayList<>();
ShopBean shopBean1 = new ShopBean("http://www.baidu.com", 12.3, "鱼肉", 1);
ShopBean shopBean2 = new ShopBean("http://www.baidu.com", 15.7, "鸡腿", 2);
list.add(shopBean1);
list.add(shopBean2);
String jsonString = JSON.toJSONString(list);
tv1.setText(list.toString());
tv2.setText(jsonString);
}
源码链接