12、Gson簡用筆記

1、基礎知識簡介html

一、Gson 是 Google 提供的用來在 Java 對象和 JSON 數據之間進行映射的 Java 類庫。能夠將一個 JSON 字符串轉成一個 Java 對象,或者反過來。java

二、JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。JSON採用徹底獨立於語言的文本格式,這些特性使JSON成爲理想的數據交換語言。易於人閱讀和編寫,同時也易於機器解析和生成。android

21世紀初,Douglas Crockford尋找一種簡便的數據交換格式,可以在服務器之間交換數據。當時通用的數據交換語言是XML,可是Douglas Crockford以爲XML的生成和解析都太麻煩,因此他提出了一種簡化格式,也就是Json。json

Json的規格很是簡單,只用一個頁面幾百個字就能說清楚,並且Douglas Crockford聲稱這個規格永遠沒必要升級,由於該規定的都規定了。數組

1) 並列的數據之間用逗號(", ")分隔。服務器

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

3) 並列數據的集合(數組)用方括號("[]")表示。ide

4) 映射的集合(對象)用大括號("{}")表示。工具

2、demo項目ui

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;
}

 3、工具類

 項目中若是屢次使用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);

4、若是此博客的內容沒法知足須要,那麼值得參考的博客網址 http://blog.csdn.net/lk_blog/article/details/7685169

相關文章
相關標籤/搜索