无法使用JSONObject更新.json文件中的子节点



我有一个.json文件,我想更改子节点值。在下面的文件中,我想将国家代码从NZ更改为DE

{
"@type": "Template",
"matches": {
"countryCode": "NZ",
"partner": "JD",
"packageId": "TEST",
"userGroup": "small",
"templateName": "rec"
}

我尝试过以下操作,但它并没有更新子节点的值。你能帮忙做这件事吗。

import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public  JSONObject readJsonFile(String CountryCode) throws IOException, ParseException 
{
String filePath = System.getProperty("user.dir") + "/TemplatesJSONPayload/" +"templates.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
jsonObject.put("countryCode", "DE");
return jsonObject;
}

如果要更改父节点中的值,则需要获取子节点对象,然后必须更改countryCode的值。

import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public  JSONObject readJsonFile(String CountryCode)throws IOException,ParseException
{
String filePath=System.getProperty("user.dir")+"/TemplatesJSONPayload/"+"templates.json";
FileReader reader=new FileReader(filePath);
JSONParser jsonParser=new JSONParser();
JSONObject jsonObject=(JSONObject)jsonParser.parse(reader);
JSONObject matches=(JSONObject)jsonObject.get("matches");
matches.put("countryCode","DE");
return jsonObject;
}

您需要先获取matches对象并放入其中,

jsonObject.getJSONObject("matches").put("countryCode", "DE");

最新更新