java - 如何向json数据添加元素

标签 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));

最佳答案

你可以使用 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")
    }

关于java - 如何向json数据添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27146518/

相关文章:

java - 从 Spring Boot 2.4.x 更新到 2.5.x 后 Jackson 模块未注册

java - 我收到此错误 : The markup in the document following the root element must be well-formed

c# - Unity Json反/序列化嵌套数据

java - 反序列化更改内部节点的 JSON

java - 在android中反序列化JSON字符串

java - Spring Boot - 如何将自定义 header 添加到 SOAP 响应?

java - 如何根据配置动态创建多个jms消息驱动 channel 适配器

java - 安卓 : Notified when all Async calls are completed

javascript - 从字符串中提取子字符串并转换为node js中的json对象

java - Jersey - Moxy 在类属性中返回附加 json