java - 向 json 对象 java 中的数组添加新元素

标签 java arrays json

我正在编写自动化脚本来验证 REST API 的 json 响应,并且我正在使用更快的 xml 来序列化 java 对象并将其转换为 json 格式。 我有一个用户案例,我必须获取 json 响应并将新的数组元素添加到现有数组并将其发回。 GET 后的 json 响应如下所示:

{
   "name":"test",
   "id":"1234",
   "nodes":[
            {
                "nodeId":"node1"
            },
            {
                 "nodeId":"node2"
            }
    ]
}

对于这个 json 响应,我需要为节点数组添加第三个条目 { "nodeId": "node3"} 然后发布此内容。

有人可以帮助我了解如何向现有数组添加新数组元素吗?

最佳答案

你可以尝试:

//Your JSON response will be in this format
String response = "{ \"name\":\"test\", \"id\":\"1234\", \"nodes\":[ { \"nodeId\":\"node1\" }, { \"nodeId\":\"node2\" } ] }";
   try {
        JSONObject jsonResponse = new JSONObject(response);
        JSONArray nodesArray = jsonResponse.getJSONArray("nodes");
        JSONObject newEntry = new JSONObject();
        newEntry.put("nodeId","node3");
        nodesArray.put(newEntry);
        jsonResponse.put("nodes",nodesArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

现在您可以根据需要发布您的 jsonResponse.toString()

关于java - 向 json 对象 java 中的数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46159471/

相关文章:

Python - JSONDecodeError : Expecting property name enclosed in double quotes

javascript - 解析一个以变量为名称的 json 对象

php - 如何在 JSON 响应中呈现 ZF2 View ?

java - 如何知道执行该类的用户有权更改系统时间?

java - 邻接表创建,内存不足错误

java - 像在 JTextArea java 中一样在 JLabel 中 append 功能?

objective-c - 快速枚举比嵌套枚举中的 for 循环慢(带有测试结果)?

java - 如何将 JPanel 与 JFrame 底部对齐(java swing)

c# - Naudio-将音频流放入值[-1,1]

java - 在 for 循环中使用数组长度不安全