gson处理多层嵌套的复杂形式的json

当一个Class的字段属性中包含另一个class时gson能正常处理吗? 最初看到网上有说使用static的说法 经验证是不需要的 直接当普通类来用就可以了。

直接使用gson.fromJson方法即可。

以下为测试代码

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对象方法

Json举例(实际上是WEB服务自动转化而来的)

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

你可能感兴趣的:(gson处理多层嵌套的复杂形式的json)