我目前正在使用 Gson 库来写入/读取 .json 文件。我有这个方法来编写 json 简介。
public static void write(String key, String value){
GeneralJsonConfig gjc = new GeneralJsonConfig();
if(key.equals("testKey")){
gjc.setaucString(value);
}
Gson gson = new Gson();
String json = gson.toJson(gjc);
try{
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
} catch(IOException e) {
}
}
但假设我有这个 .json:
{"testKey": "some test", "testKey2": "test 3"}
我只想将 thestKey 从“某些测试”更改为另一个文本,其他键/值将保持原样,但使用我的方法,其他值/键就会消失,我该如何解决这个问题让其他键/值保留?
更新: 找到了基于 sam100rav 答案的答案,我只需读取完整的 json 文件来获取值,然后用我想要完成的更改再次写入它们:
public static void write(String key, String value){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try{
BufferedReader br = new BufferedReader(new FileReader(launcherConfigFile));
GeneralJsonConfig gjcObject = gson.fromJson(br, GeneralJsonConfig.class);
if(key.equals("testKey")){
gjc.setaucString(value);
}
String json = gson.toJson(gjcObject);
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
br.close();
} catch (IOException e){
main.er.LogError("23", "");
}
最佳答案
JSONObject obj = new JSONObject();
obj.put("testKey", "some test");
obj.put("testKey2", "test 3");
if(key.equals("testKey")){
obj.put("testKey", value);
}
String json = obj.toString();
try{
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
}
关于java - Gson库写入文件并只更改特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31494720/