gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:13:36 24 4
gpt4 key购买 nike

我有一个类似于下面的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com