其他分享
首页 > 其他分享> > JSON数据格式转换2-对象和数组修改

JSON数据格式转换2-对象和数组修改

作者:互联网

修改内容

使用fastjson对JSON内容的转换

如下目标JSON字符串和希望结果字符串,修改json数组里面的内容和json对象里面的内容

目标JSON字符串

{
	"result": {
		"data": [
			{
				"code": "CF327",
				"value": "0.0016592020664306757"
			},
			{
				"code": "CF327",
				"value": "0.0016592020664306757"
			}
		],
		"message": "计算成功!",
		"location":{
			"province":"zhejiang",
			"city":"hangzhou"
		},
		"status": 0
	}
}

希望结果字符串

{
	"result": {
		"data": [
			{
				"code": "CF327",
				"value": "0.0016592020664306757"
			},
			{
				"code": "CF326",
				"value": "0.001"
			}
		],
		"message": "计算成功!",
		"location":{
			"province":"zhejiang",
			"city":"shaoxin"
		},
		"status": 0
}
处理步骤
JSONObject inputjson = JSON.parseObject("{\n" +
        "\t\"result\": {\n" +
        "\t\t\"data\": [\n" +
        "\t\t\t{\n" +
        "\t\t\t\t\"code\": \"CF327\",\n" +
        "\t\t\t\t\"value\": \"0.0016592020664306757\"\n" +
        "\t\t\t},\n" +
        "\t\t\t{\n" +
        "\t\t\t\t\"code\": \"CF327\",\n" +
        "\t\t\t\t\"value\": \"0.0016592020664306757\"\n" +
        "\t\t\t}\n" +
        "\t\t],\n" +
        "\t\t\"message\": \"计算成功!\",\n" +
        "\t\t\"location\":{\n" +
        "\t\t\t\"province\":\"zhejiang\",\n" +
        "\t\t\t\"city\":\"hangzhou\"\n" +
        "\t\t},\n" +
        "\t\t\"status\": 0\n" +
        "\t}\n" +
        "}");

System.out.println("修改前inputjson:"+inputjson);

//解析数据
JSONObject resultjson = inputjson.getJSONObject("result");

JSONObject locationjson = resultjson.getJSONObject("location");
JSONArray datajson = resultjson.getJSONArray("data");

//修改数据
if(locationjson.containsKey("city")){
    locationjson.put("city","shaoxin");
}
if(datajson.size()>=1){
    JSONObject datajsontwo = datajson.getJSONObject(1);
    datajsontwo.put("code","CF326");
    datajsontwo.put("value","0.001");
}

System.out.println("修改后inputjson:"+inputjson);

标签:city,code,CF327,value,JSON,数组,数据格式,inputjson
来源: https://www.cnblogs.com/yorkiiz/p/16318781.html