java - 无法使用 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;
}
推荐阅读
- qt - 如何通过单击 Qt Widget Application 中的按钮转到其他表单
- node.js - 无法通过节点中的 post 方法将 csv 导入 mongo
- html - 为 SVG 图案背景设置动画
- c++ - 崇高的文本语法突出显示损坏
- python - ValueError:您必须指定 input_ids 或 inputs_embeds
- python - 带有 pytorch 的 RNN,以单个神经元作为输出
- c++ - 如何在空构造函数中初始化 std::chrono::miliseconds?
- flutter - 如何将 ModalProgressHUD 包含到另一个容器中?
- python - 模型输出的维度和预测值不同,但是 model.fit 它仍然不会抛出错误
- html - 无法在可滚动容器内使 div 全宽