我正在编写自动化脚本来验证 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/