我正在使用 Gson 写入和读取文件。
每次创建用户时,我都会附加一行显示用户名和 ID。
我使用以下代码执行此操作(UserAccount 是我的 pojo 类,br 是我的缓冲阅读器)::
UserAccount accountObj = new UserAccount();
FileWriter writer = new FileWriter("store.json", true);
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
String json = gson.toJson(accountObj);
writer.write(json);
writer.close();
这会生成 json 文件,其工作原理如下:::
{"USER":"noob123","ID":"99"}
当新用户执行此操作时,它将像这样附加下一行::
{"USER":"noob123","ID":99}{"USER":"pro321","ID":100}
当我尝试读取此 json 文件时,出现以下错误::
"use JsonReader.setLenient(true) to accept malformed JSON at line 1, column 36"
所以我知道它可能格式不正确,可能需要类似::
{"ACCOUNT":{"USER":"noob123","ID":99},"ACCOUNT":{"USER":"pro321","ID":100}}
我花了一些时间尝试以这种格式创建 JSON,或者至少在使用匹配的用户名时引用正确的用户 key 。非常感谢任何帮助。
谢谢
最佳答案
您应该使用 JSONArray 将此信息保存到文件中。然后您可以将文件内容读取到UserAccount
列表中,并将新对象添加到该列表中。
然后你应该覆盖文件的内容。
例如。 :
UserAccount accountObj = new UserAccount();
accountObj.setUser(NewUserMethod());
accountObj.setID(NewIDMethod());
List<UserAccount> userAccounts = gson.fromJson(<jsonContent>, new TypeToken<List<UserAccount>>() {
}.getType());
userAccounts.add(accountObj);
String json = gson.toJson(userAccounts);
writer.write(json);
writer.close();
关于Java JSON - gson - 附加新数据,格式错误的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791384/