您的位置:首页 > 其它

十二、Gson简用笔记

2015-12-02 18:41 429 查看
一、基础知识简介

1、Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

2、JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

21世纪初,Douglas Crockford寻找一种简便的数据交换格式,能够在服务器之间交换数据。当时通用的数据交换语言是XML,但是Douglas Crockford觉得XML的生成和解析都太麻烦,所以他提出了一种简化格式,也就是Json。

Json的规格非常简单,只用一个页面几百个字就能说清楚,而且Douglas Crockford声称这个规格永远不必升级,因为该规定的都规定了。

1) 并列的数据之间用逗号(", ")分隔。

2) 映射用冒号(": ")表示。

3) 并列数据的集合(数组)用方括号("[]")表示。

4) 映射的集合(对象)用大括号("{}")表示。

二、demo项目

2.1 项目结构图



2.2 MainActivity中的代码如下:

package com.example.administrator.testdemo;

import android.app.Activity;
import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
private Gson gson = new Gson();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONObject jsonObject = generataJSONObjectData();
SuitModelListBO suitModelListBO = gson.fromJson(jsonObject.toString(), new TypeToken<SuitModelListBO>() {
}.getType());     //将json类型的数据转化为Bean类型数据

List<ModelBO> modelList = suitModelListBO.modleList;
String modelListStr = gson.toJson(modelList);    //将Bean类型数据转化为json类型数据
List<ModelBO> ChildModelBoList = gson.fromJson(modelListStr, new TypeToken<ArrayList<ModelBO>>() {
}.getType()); //将json类型的数据转化为Bean类型数据

}

/*生成JSONObject类型的数据
*/


private JSONObject generataJSONObjectData() {
JSONObject jsonObject = new JSONObject();
try {
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("status", 1);
jsonObject1.put("channelId", "public1");
jsonObject1.put("iconUrl", "");
jsonObject1.put("modelVersion", 1);
jsonObject1.put("iconAction", "");
jsonObject1.put("label", "wealth");
jsonObject1.put("childModelTree", "");
jsonObject1.put("id", 11);
jsonObject1.put("childModelList", "12,13,14,15,16,17,18,19,20");
jsonObject1.put("name", "财富");
jsonObject1.put("phoneSys", "Android");
jsonObject1.put("action", "");
jsonObject1.put("redMark", "");
jsonObject1.put("redirectUrl", "");
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("status", 1);
jsonObject2.put("channelId", "public1");
jsonObject2.put("iconUrl", "");
jsonObject2.put("modelVersion", 1);
jsonObject2.put("iconAction", "");
jsonObject2.put("label", "flowpay");
jsonObject2.put("childModelTree", "");
jsonObject2.put("id", 12);
jsonObject2.put("childModelList", "");
jsonObject2.put("name", "流量宝");
jsonObject2.put("phoneSys", "Android");
jsonObject2.put("action", "");
jsonObject2.put("redMark", "");
jsonObject2.put("redirectUrl", "http://bao.e.189.cn/portal/rechargeFlowByCoin.do");
JSONObject jsonObject3 = new JSONObject();
jsonObject3.put("status", 1);
jsonObject3.put("channelId", "public1");
jsonObject3.put("iconUrl", "");
jsonObject3.put("modelVersion", 1);
jsonObject3.put("iconAction", "");
jsonObject3.put("label", "phonePackage");
jsonObject3.put("childModelTree", "");
jsonObject3.put("id", 13);
jsonObject3.put("childModelList", "");
jsonObject3.put("name", "套餐查询");
jsonObject3.put("phoneSys", "Android");
jsonObject3.put("action", "");
jsonObject3.put("redMark", "");
jsonObject3.put("redirectUrl", "");
JSONArray modleList = new JSONArray();
modleList.put(jsonObject1);
modleList.put(jsonObject2);
modleList.put(jsonObject3);
jsonObject.put("msg", "success");
jsonObject.put("modleList", modleList);
jsonObject.put("result", "0");
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
}


2.3 ModelBO中的代码如下:

package com.example.administrator.testdemo;

public class ModelBO {
public long id;
public String channelId;
public String name;
public String iconUrl;
public String phoneSys;
public long modelVersion;
public String action;
public String redMark;
public String iconAction;
public String label;
public String redirectUrl;
public long status;
public String childModelTree;
public String childModelList;
public ModelBO() {
}

public ModelBO(long id, String channelId,
String name, String iconUrl,
String phoneSys, long modelVersion,
String action, String redMark,
String iconAction, String label,
String redirectUrl, long status,
String childModelTree, String childModelList) {
this.id = id;
this.channelId = channelId;
this.name = name;
this.iconUrl = iconUrl;
this.phoneSys = phoneSys;
this.modelVersion = modelVersion;
this.action = action;
this.redMark = redMark;
this.iconAction = iconAction;
this.label = label;
this.redirectUrl = redirectUrl;
this.status = status;
this.childModelTree = childModelTree;
this.childModelList = childModelList;
}
}


2.4 SuitModelListBO中的代码如下:

package com.example.administrator.testdemo;

import java.util.List;

public class SuitModelListBO {
public List<ModelBO> modleList;
public Long timeStamp;
public int result;
public String msg;
}


三、工具类

项目中如果多次使用GSON解析数据的时候,避免多次创建Gson对象,可以创建一个工具类实现JSONObject转化为实体类或实体类转化为JSONObject

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class DataParser {
// 使用Gson将jsonString转化为javaBean object
public static <T> T stringToModelObject(String jsonString, Class<T> cls) {
try {
T t = null;
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);

return t;
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}

// 使用Gson进行解析 List<Object>
public static <T> List<T> getGsonArray(String jsonString, Class<T> cls) {
try {
List<T> list = new ArrayList<T>();

Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
}.getType());

return list;
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}


3.1 此工具方法使用例子

3.1.1 一个接口的返回GSONObject结果如下所示:

返回结果
{
"items": [
{
"beginDate": "20140101000000",
"endDate": "20140131000000",
"items": [
{
"balanceAmount": "12",
"beginTime": "Wed Jan 01 00:00:00 GMT+08:00 2014",
"endTime": "Fri Jan 31 00:00:00 GMT+08:00 2014",
"ownerID": null,
"ownerType": "80A",
"ratableAmount": "12",
"ratableResourceID": "500246906",
"ratableResourcename": "后付费乐享3G主副卡上网版国内点对点彩信条数",
"unitTypeId": "2"
},
{
"balanceAmount": "55",
"beginTime": "Wed Jan 01 00:00:00 GMT+08:00 2014",
"endTime": "Fri Jan 31 00:00:00 GMT+08:00 2014",
"ownerID": null,
"ownerType": "80A",
"ratableAmount": "60",
"ratableResourceID": "500246905",
"ratableResourcename": "后付费乐享3G主副卡上网版国内点对点短信条数",
"unitTypeId": "2"
}
],
"productOFFName": "后付费乐享3G主副卡上网版_2011年9月"
}
],
"paraFieldResult": null,
"serviceResultCode": "0",
"totalBalanceAvailable": null,
"result": "0"
}
错误返回结果
Json示例:
Content-type: text/html; charset=utf-8
{
“result”:- 101,
“msg”:”发生未知错误”
}


3.2 此接口对应的实体QueryCTPackageResponseBo的定义如下所示:

public class QueryCTPackageResponseBo  {

public int result;//0 表示查询成功,其他表示查询失败,参考错误码对应表
public String paraFieldResult;//错误信息
public int serviceResultCode; //业务结果码,和result一致
public int totalBalanceAvailable;//实时可用总余额
public String msg;
public List<PackageList> items;
}


PackageList的定义如下所示:


public class PackageList {
public List<PackageBean> items;
public String beginDate;
public String endDate;
public String productOFFName;

}


PackageBean的定义如下所示:


package cn.com.chinatelecom.account.bean;

import java.io.Serializable;

public class PackageBean implements Serializable{
public int balanceAmount;
public String beginTime;
public String endTime;
public long ownerID;
public String ownerType;
public int ratableAmount;
public long ratableResourceID;
public String ratableResourcename;
public int unitTypeId;
public String nameType;

}


3.3 将从服务器端返回的GSONObject转化为对应的实体:

QueryCTPackageResponseBo queryCTPackageResponseBo = DataParser
.stringToModelObject(response.toString(),
QueryCTPackageResponseBo.class);


四、如果此博客的内容无法满足需要,那么值得参考的博客网址 /article/1409637.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: