JSON使用小记

JSON使用小记

JSON是什么
JSON(JavaScript对象表示法 JavaScript Object Notation),是存储和交换文本信息的语法,轻量级的文本数据交换格式,类似XML,但是比XML更小、更快、更容易解析。 JSON独立于各种编程语言平台,并且几乎所有的主流编程语言都内置了对JSON数据格式的支持。

JSON语法规则
JSON语法是JavaScript对象表示法语法的子集:

数据以名/值 对的形式表示
数据之间以逗号分隔
花括号保存对象
方括号保存数组

JSON值
JSON名值对包括字段名称(包含在双引号中),后面一个冒号,然后是值,如:

"username": "czc"

JSON值可以包含以下多种类型:

数字(整数和浮点数)
字符串(在双引号中)
逻辑值(truefalse)
数组(在方括号中)
对象(在花括号中)
null

JSON对象和JSON数组
JSON对象包含在花括号中,可以包含多个名/值对,其值可以为数组;JSON数组包含在方括号中,可以包含多个对象。JSON既可以以花括号开头,也可以以方括号开头,JSON对象和JSON数组可以互相嵌套,如:

{
"cartItems":[
{"accountNum":0.0,"addPrice":0.0,"addPriceMode":0,"addType":0,"compulsory":false,"doubleUnitStatus":
0,"index":"99933759jJBEzpghmppFNFAOotV0yMFz","isWait":0,"kindType":1,"menuId":"999337595fa39b9d015
fba559ef608de","menuName":"牛排(示例)","num":1.0,"present":0,"source":"CLOUD_CASH006","uid":"2d4c
5e81ee0048758b3e1df12c732a2e"}
],
"customerRegisterId":"2d4c5e81ee0048758b3e1df12c732a2e","entityId":"99933759","seatCode":"107","so
urce":"CLOUD_CASH006"
}

JSON文件
json文件的后缀为:”.json”
JSON文件的MIME类型为:“application/json”

JSON解析和序列化
早期的JSON解析器基本上就是使用JavaScript的eval()函数。由于JSON是JavaScript语法的子集,因此eval()函数可以解析并返回JavaScript对象和数组。
ECMAScript 5对解析JSON的行为进行了规范,定义了全局对象JSON。
JSON解析
使用JSON.parse()把字符串解析为JSON对象或数组。

//返回JSON对象
var jsonStr1 = '{"username":"Jessica","age":23}';
var jsonObj = JSON.parse(jsonStr1);
console.log(jsonObj.username); //Jessica
console.log(jsonObj.age) //23

//返回JSON数组
var jsonStr2 = '[{"username":"Jacky","age":30}, {"username":"Jessica","age":23}]';
var jsonArr = JSON.parse(jsonStr2);
for(var i=0;i<jsonArr.length;i++) {
    console.log(jsonArr[i].username); //Jacky Jessica
}

JSON序列化

使用JSON.stringify()把JSON对象或数组序列化为字符串。

//序列化JSON对象
var jsonObj = {
    "username": "Jessica",
    "age": 23
};
var jsonStr1 = JSON.stringify(jsonObj);
console.log(jsonStr1); //{"username":"Jessica","age":23}

//序列化JSON数组
var jsonArr = [
    {"username":"Jacky","age":30},
    {"username":"Jessica","age":23}
];
var jsonStr2 = JSON.stringify(jsonArr, null, 2);
console.log(jsonStr2); 

PS:最后附带一个实际项目里的操作json的例子

加入购物车
{“cartItems”:[{“accountNum”:0.0,”addPrice”:0.0,”addPriceMode”:0,”addType”:0,”compulsory”:false,”doubleUnitStatus”
:0,”index”:”99933759jJBEzpghmppFNFAOotV0yMFz”,”isWait”:0,”kindType”:1,”menuId”:”999337595fa39b9
d015fba559ef608de”,”menuName”:”牛排(示例)”,”num”:1.0,”present”:0,”source”:
“CLOUD_CASH006”,”uid”:”2d4c5e81ee0048758b3e1df12c732a2e”}],”customerRegisterId”:”2d4c5e81ee0048
758b3e1df12c732a2e”,”entityId”:”99933759”,”seatCode”:”107”,”source”:”CLOUD_CASH006”}
sourceId: menuId

加菜
{“cartTime”:1517279101894,”entityId”:”99933759”,”industryCode”:0,”memberId”:”2d4c5e81ee0048758b3e
1df12c732a2e”,”opUserId”:”b45921a14ec844ca9634d9742733d0b1”,”orderId”:”999337596140d2d3016144de3
791000f”,”seatCode”:”107”}
sourceId:orderId

云收银赠菜
{“modifyTime”:1517301249,”opUserId”:”b45921a14ec844ca9634d9742733d0b1”,”num”:1.0,”instanceId”:”9
99337596146220d01614633b5770001”,”entityId”:”99933759”,”accountNum”:1.0,”memo”:”“}
sourceId:instanceId

private String getSourceId(String method, OpInfoParams opInfoParams) {
        String json = opInfoParams.getJson();
        JSONObject jsonObject = JSON.parseObject(json);
        String sourceId;
        if ("com.dfire.tp.client.service.ITradePlatformService.modifyInstancePrice".equals(method) || "com.dfire.tp.client.service.ITradePlatformService.modifyInstanceWeight".equals(method) || "com.dfire.tp.client.service.ITradePlatformService.cancelInstance".equals(method) || "com.dfire.tp.client.service.ITradePlatformService.freeInstance".equals(method)){
            sourceId = jsonObject.getString("instanceId");
        }else if ("com.dfire.cashsoa.loginByAppKey".equals(method) || "com.dfire.cashsoa.login".equals(method)){
            sourceId = opInfoParams.getMobile();
        }else if ("com.dfire.soa.cloudcash.loginByTrainNo".equals(method)){
            sourceId = opInfoParams.getTrainNo();
        }else if ("com.dfire.consumer.modifyCartItem".equals(method)||"com.dfire.soa.cloudcash.ICartBaseClientService.modifyCartItem".equals(method)){
            String cartItemJson = opInfoParams.getCartItemModifyRequest();
            JSONObject jsonObject1 = JSON.parseObject(cartItemJson);
            sourceId = ((JSONObject)((JSONArray)jsonObject1.get("cartItems")).get(0)).getString("menuId");
        }else if ("com.dfire.soa.cloudcash.changeOrder".equals(method) || "com.dfire.dpush.bindSeat".equals(method) || "com.dfire.soa.cloudcash.bindSeat".equals(method) || "com.dfire.soa.cloudcash.retainOrder".equals(method)||"com.dfire.soa.cloudcash.ILoginClientService.switchShopByAppKey".equals(method)||"com.dfire.cashsoa.switchShop".equals(method)){
            sourceId = opInfoParams.getUserId();
        }else if("com.dfire.soa.cloudcash.ICartBaseClientService.clearCart".equals(method)|| "com.dfire.consumer.clearCart".equals(method)){
            String cartClearRequest = opInfoParams.getCartClearRequest();
            JSONObject jsonObject1 = JSON.parseObject(cartClearRequest);
            sourceId = jsonObject1.getString("customerRegisterId");
        }else if ("com.dfire.tp.client.service.ITradePlatformService.submitOrder".equals(method) || "com.dfire.tp.client.service.ITradePlatformService.auditOrder".equals(method)){
            sourceId = jsonObject.getString("opUserId");
        }else if ("com.dfire.msstate.saveOrUpdateMenuBalance".equals(method)){
            sourceId = opInfoParams.getMenuId();
        }else if ("com.dfire.msstate.clearMenuBalanceFromCloudCash".equals(method) || "com.dfire.msstate.clearMenuBalanceFromCloudCash".equals(method)){
            sourceId = opInfoParams.getOp_user_id();
        } else {
            sourceId = jsonObject.getString("orderId");
        }
        return sourceId;
    }

猜你喜欢

转载自blog.csdn.net/xiaozhouchou/article/details/79260785
今日推荐