![](/img/trans.png)
[英]Groovy read json-file, add new key : value and write back (Jenkins)
[英]Add new content to JSON-File
我有一個名為“ user.json”的json文件。 現在,我想添加一個新用戶。 我知道如何獲取文件的內容並將其放在字符串中,但是我不知道如何正確添加新內容。 “ jsonString”是“ user.json”的內容
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
輸出為:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
但是應該是:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
有人知道該怎么做嗎? 我查了一下,但所有示例都對我不起作用,因為當我嘗試時
JSONObject object = new JSONObject(jsonString);
要么
JSONArray array = new JSONArray(jsonString);
我總是得到“構造函數未定義”。
編輯:user.json的內容
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:我解決了問題
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
似乎您正在向jsonObject
添加字段,並且您想要執行的操作基本上是將新對象添加到inner json array
(在這種情況下,該字段稱為"user"
嘗試這個:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
您可以使用fromObject()
方法:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.