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

Java 无法使用JSONObject更新.json文件中的子节点,java,json,Java,Json,我有一个.json文件,我想更改子节点值。 在下面的文件中,我想将国家代码从NZ更改为DE { "@type": "Template", "matches": { "countryCode": "NZ", "partner": "JD", "packageId": "TEST", "userGroup": "small", "templateName": "rec" } 我尝试了以下方法,但它不更新子节点值。你能帮忙做这件事吗 im

我有一个.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;
    }

您需要首先获取
匹配的
对象并将其放入其中

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

如果要更改父节点中的值,则需要获取子节点对象,然后必须更改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;
}

尝试类似于jsonObject.getJSONObject(“匹配”).put(“countryCode”、“DE”);谢谢@Shubham,现在一切正常。