您的位置:首页 > Web前端 > JavaScript

构造JSON和解析JSON

2015-10-30 20:21 561 查看
如果要构造一个

{
    "Req": {
              "serialID":"20140729153630100002",
        "bizType": "queryAccount"
    },
    "ReqBean": {
        "userCode": "18616029486"
    }
}这样的字符串,如何去构造JSON
      //构造传送报文
       Map<String,Map<String,String>> resultMap = new HashMap<String,Map<String,String>>();
       //报文头
       Map<String,String> reqMap = new HashMap<String,String>();
       SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssssssss");
       String date = format.format(new Date());
       reqMap.put("serialID", date);
       reqMap.put("bizType", "queryAccount");
       resultMap.put("Req", reqMap);
       Map<String,String> reqBeanMap = new HashMap<String,String>();
       reqBeanMap.put("userCode", userCode);
       resultMap.put("ReqBean", reqBeanMap);

JSON如何解析:      

{

    "respBean": {

        "balance": "5000",

        "balanceA": 0,

        "closeTime": null,

        "balanceB": 5000,

        "balanceC": 0,

        "userCode": "18616029486",

        "accountStatus": "01",

        "lastUpdateTime": "2014-07-29 16:08:24",

        "accountType": "01",

        "openTime": "2014-07-29 16:05:27"

    },

    "resp": {

        "respCode": "0000",

        "serialID": "20140729153630100002",

        "bizType": "queryAccount",

        "respMsg": "成功!"

    }

}

先取到respBean的值,然后在respBean里面取相应的值

//整个json字符串转化成JSONObject对象

JSONObject jsonObject = JSONObject.fromObject(JSON字符串);
//取JSONObject里面的respBean的值

JSONObject respBean = jsonObject.getJSONObject("respBean");

//挨个取就可以了,就好比拆包装一样,一层一层的拆就好
String balance = respBean.getString("balance");
.....

只是一种取值方式,还有JSONArray的取值方式。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JSON