Java 如何向json数据添加元素

Java 如何向json数据添加元素,java,json,Java,Json,我有一个类似下面这样的json。我想阅读它并添加两个属性,比如国家和州 [ { "id": "123", "testname": "test123", "name": "John Doe", "active": true, "type": "test6" } { "id": "456", "testname": "test564", "name":

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

[
    {
        "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));
“type”之后缺少逗号:“test6”

{
“id”:“123”,
“testname”:“test123”,
“姓名”:“约翰·多伊”,
“主动”:正确,

“type”:“test6”您可以使用for循环在JSONArray上迭代,一旦您有了jsonObject,就可以使用put for这样的额外属性

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")
    }

for(int i=0;我可能值得一提,以澄清这是确切的JSON,而不是他们刚刚为示例键入的内容。如果是@christopher所说的。那么我真的帮不了你。抱歉=)
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")
    }