我有一个名为test.json的json文件,如下所示:
{
"Added": {
"type": "K",
"newmem": {
"IDNew": {
"id": "777709",
"type": "LOP"
},
"birthDate": "2000-12-09"
},
"code": "",
"newest": {
"curlNew": "",
"addedForNew": ""
}
}
}
我可以使用以下代码更新json中的id并写回文件:
FileReader reader = new FileReader(filePath); //where file path = D://.../test.json
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONObject addedObj = (JSONObject) jsonObject.get("Added");
JSONObject newmemObject =(JSONObject) addedObj.get("newmem");
JSONObject idNewObj =(JSONObject) newmemObject.get("IDNew");
idNewObj.put("id",12345);
FileOutputStream outputStream = new FileOutputStream(filePath);
byte[] strToBytes = jsonObject.toString().getBytes();
outputStream.write(strToBytes);
然而,它不是用更新的值重写整个json,而是只写:
{
"id": "777709",
"type": "LOP"
}
我可以做什么来重写整个json,而不是只重写它的嵌套部分?