首页 > 解决方案 > 无法使用 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;
    }

标签: javajson

解决方案


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

推荐阅读