Android筆記:gson處理多層嵌套的複雜形式的json

當一個Class的字段屬性中包含另外一個class時gson能正常處理嗎? 最初看到網上有說使用static的說法 經驗證是不須要的 直接當普通類來用就能夠了。java

直接使用gson.fromJson方法便可。json

如下爲測試代碼服務器

import java.io.Serializable;
@SuppressWarnings("serial")
public class House implements Serializable {
    public House() {
    }

    private int ID;
    private String HouseName;
    private String HouseNo;
    private Integer State;
    private Integer ParentID;
    private Integer UserID;
    private String Remark;
    private Long UpSB;
    private Integer AgentID;

    private HousePars Pars;
    private CtrMP3 Mp3;
    private ZigbeeSB Zigbeesb;

    /**
     * 主鍵ID
     */
    public final void setID(int value) {
        ID = value;
    }

    public final int getID() {
        return ID;
    }

    /**
     * 名稱
     */
    public final void setHouseName(String value) {
        HouseName = value;
    }

    public final String getHouseName() {
        return HouseName;
    }

    /**
     * 房間編號
     */
    public final void setHouseNo(String value) {
        HouseNo = value;
    }

    public final String getHouseNo() {
        return HouseNo;
    }

    /**
     * 狀態
     */
    public final void setState(Integer value) {
        State = value;
    }

    public final Integer getState() {
        return State;
    }

    /**
     * 上級區域
     */
    public final void setParentID(Integer value) {
        ParentID = value;
    }

    public final Integer getParentID() {
        return ParentID;
    }

    /**
     * 所屬用戶
     */
    public final void setUserID(Integer value) {
        UserID = value;
    }

    public final Integer getUserID() {
        return UserID;
    }

  
    public final void setRemark(String value) {
        Remark = value;
    }

    public final String getRemark() {
        return Remark;
    }

    /**
     * 客戶編號
     * 
     * @return
     */
    public Integer getAgentID() {
        return AgentID;
    }

    public void setAgentID(Integer agentID) {
        AgentID = agentID;
    }

    /**
     * 協調器地址
     * 
     * @return
     */
    public Long getUpSB() {
        return UpSB;
    }

    public void setUpSB(Long upSB) {
        UpSB = upSB;
    }

    public HousePars getPars() {
        return Pars;
    }

    public void setPars(HousePars pars) {
        Pars = pars;
    }

    public CtrMP3 getMp3() {
        return Mp3;
    }

    public void setMp3(CtrMP3 mp3) {
        Mp3 = mp3;
    }

    public ZigbeeSB getZigbeesb() {
        return Zigbeesb;
    }

    public void setZigbeesb(ZigbeeSB zigbeesb) {
        Zigbeesb = zigbeesb;
    }

    
}

上述類中 CtrMP3 ,ZigbeeSB,HousePars 都是單獨的類網絡

從JSON轉爲java對象方法app

Json舉例(其實是WEB服務自動轉化而來的)post

{"d":{"__type":"Model.House","Zigbeesb":{"__type":"IntelligenceFactory.Model.ZigbeeSB","MacHex":"D7D15702004B1200","ID":69,"Jiange":7098850,"MacAddrstr":"D7D15702004B1200","ParentMacstr":"D7D15702004B1200","RootMacstr":"0000000000000000","MacAddr":-2895437419316047360,"Name":"協調器","ModelNo":null,"UserID":1,"ParentMac":-2895437419316047360,"RootMac":0,"IsMain":true,"Description":"","SortIndex":null,"Signal":255,"LastTime":"\/Date(1389414412000)\/","Type":null,"HouseID":23,"Remark":"7098850","AgentID":1},"Mp3":{"__type":"Model.CtrMP3","Jiange":null,"ID":19,"Name":"播放器2","MacAddr":null,"NameCode":"114","MacID":null,"UserID":null,"HouseID":1,"Type":null,"State":1,"LastTime":null,"Position":"","Direction":"","Value1":1,"Value2":2,"Value3":null,"Value4":null,"Value5":null,"Value6":null,"OtherValue":"","Remark":"","LinkState":null,"AgentID":1},"Pars":{"ID":1,"HouseID":23,"State1":0,"State2":null,"OtherState":"","Pars1":"2","Pars2":"10","OthePars":"","LastTime":null,"Description":"測試房間MP3"},"MacID":null,"ID":23,"HouseName":"admin","HouseNo":"02","State":1,"ParentID":null,"UserID":1,"Remark":"","UpSB":-2895437419316047360,"AgentID":1}}

 

/**
     * 獲取當前房間參數信息
     * 
     * @param houseid 房間ID
     * @param hashmap 成功失敗標誌
     * @return 返回House參數信息
     * @throws UnsupportedEncodingException
     * @throws JSONException
     */
    @SuppressWarnings("finally")
    public static House GetHousePars(int houseid,
            HashMap<String, Integer> hashmap)
            throws UnsupportedEncodingException, JSONException {
        Log.i(tag, STRUrl);
        int flag = 0;
        House ur = null;
        String tag = "httppost";
        Log.i(tag, "獲取房間信息");
        // 設置服務地址
        String Url = STRUrl + "InteWebService.asmx/GetHouse";
        HttpPost request = new HttpPost(Url);// 定義一個HTTP請求
        request.addHeader("Content-Type", "application/json; charset=utf-8");// 設置返回的內容爲json格式
        // Post參數傳遞 JSON格式
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("houseid", houseid);// 傳參,若是想傳遞兩個參數則繼續添加第二個參數jsonParams.put("param2Name","param2Value")
        Log.i(tag, "houseid=" + houseid);
        HttpEntity bodyEntity = new StringEntity(jsonParams.toString(), "utf8");// 參數必須也得是JSON數據格式的字符串才能傳遞到服務器端,不然會出現"{'Message':'strName是無效的JSON基元'}"的錯誤
        request.setEntity(bodyEntity);
        HttpClient httpClient = new DefaultHttpClient();
        String res = "";
        try {
            Log.i(tag, "開始執行請求GetHousePars");
            Log.i(tag, Url);
            HttpResponse response = httpClient.execute(request);
            int state = response.getStatusLine().getStatusCode();
            Log.i(tag, "返回狀態" + state);
            if (state == 200) {
                // 200表示鏈接成功 404 鏈接失敗
                Log.i(tag, "狀態200鏈接成功");
                HttpEntity entity = response.getEntity();// 獲取返回結果
                res = EntityUtils.toString(entity);
                Log.i(tag, res);
                GsonBuilder gsonb = new GsonBuilder();
                // Json中的日期表達方式沒有辦法直接轉換成咱們的Date類型, 所以須要單獨註冊一個Date的反序列化類.
                DateDeserializer ds = new DateDeserializer();
                // 給GsonBuilder方法單獨指定Date類型的反序列化方法
                gsonb.registerTypeAdapter(java.util.Date.class, ds);
                Gson gson = gsonb.create();
                JSONObject resultJSON = new JSONObject(res);
                String data = resultJSON.get("d").toString();
                Log.i(tag, data);
                if ("null" != data) {
                    Log.i(tag, "返回不爲null開始轉換");
                    // 登陸成功 返回用戶信息 注意時間格式的提取
                    ur = gson.fromJson(data, House.class);
                    if (ur != null) {
                        flag = 1;
                        hashmap.put("flag", flag);
                        return ur;
                    }
                } else {
                    // 沒有返回用戶信息
                    Log.i(tag, "返回爲null");
                    flag = 0;// 房間信息不存在
                    hashmap.put("flag", flag);                  
                }

            } else {
                flag = 2;// 網絡鏈接異常
                hashmap.put("flag", flag);
                Log.i("httppost", "鏈接失敗"
                        + response.getStatusLine().getStatusCode());
            }

        } catch (Exception e) {
            flag = -1;// 程序異常
            hashmap.put("flag", flag);
            Log.i("httppost", "獲取信息異常" + e.getMessage());
        } finally {
            hashmap.put("flag", flag);
            Log.i("httppost", "關閉try");
            return ur;
        }
    }

接收後直接按普通嵌套類使用便可。測試

相關文章
相關標籤/搜索