如何将元素添加到json数据

时间:2014-11-26 10:17:51

标签: java json

我有一个类似下面的json。我想阅读它并添加2个属性,如国家和州

[
    {
        "id": "123",
        "testname": "test123",
        "name": "John Doe",
        "active": true,
        "type": "test6"
    }

 {
        "id": "456",
        "testname": "test564",
        "name": "Ship Therasus",
        "active": true,
        "type": "test7"
    }
]

结果json

   [
    {
        "id": "123",
        "testname": "test123",
        "name": "John Doe",
        "active": true,
        "type": "test6",
        "country":"USA",
         "state":"KA"
    }

 {
        "id": "456",
        "testname": "test564",
        "name": "Ship Therasus",
        "active": true,
        "type": "test7",
         "country":"UK",
         "state":"MA"
    }
]

我正在做这样的事情,我尝试了JSONObject但没有输出。

JSONArray xmlJSONObj2 = new JSONArray(output);
        System.out.println("Output from Server .... \n"+xmlJSONObj2.get(0));

2 个答案:

答案 0 :(得分:2)

你可以使用for循环遍历JSONArray,一旦你有了jsonObject,就把put用于这样的额外属性

for(int i=0;i<jsonArray.length();i++){
        JSONObject json = jsonArray.getJSONObject(i);
        // do this for all remaining field
        if(json.has("id")){
            String id = json.get("id").toString();
        }
        // finally put extra attributes to that jsonobject
        json.put("country", "USA");
        json.put("state", "KA")
    }

答案 1 :(得分:0)

在&#34;&#34;&#34; test6&#34;

之后错过了逗号
{
    "id": "123",
    "testname": "test123",
    "name": "John Doe",
    "active": true,
    "type": "test6" <------
    "country":"USA",
     "state":"KA"
}