所以我在正确创建 Json 文件时遇到了麻烦。 我拥有的: 1.Gson库 2. 尝试在 Json 中写入一个新用户,如下所示:
public static void writeUserBD(String name, String surname, int age) {
//writing in a Json format
JSONObject writeOne = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0; i< arr.size() ; i++)
{
writeOne.put("name", name);
writeOne.put("surname", surname);
writeOne.put("age", new Integer(age));
arr.add(writeOne);
writeOne = new JSONObject();
}
//creating dir&file and writing in it
try {
File dir = new File("Test");
dir.mkdir();
File f = new File("Test/TestUser.json");
if (!dir.exists()) {
dir.mkdirs();
} else if (!f.exists()) {
f.createNewFile();
}
//here comes writing encoding problem ! ! !
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f.getAbsoluteFile(), true), Charset.forName("UTF-8")));
try {
bw.write(arr + " " + "\n");
} finally {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
但是如果我重新加载我的应用程序并尝试编写一个新的应用程序,它将编写一个新的 JSONObject 并且我的输出如下:
[{}]
[{}]
在这种情况下,我无法解析我的 json 文件(用于创建简单的登录),我收到类似 "unexpected token [[]"
的错误,据我了解,发生这种情况是因为文件中超过 1 个 jsonobject .
所以我的问题是:如何以我可以传递的正确格式在 json 文件中写入新用户数据(即使应用程序已重新加载),例如 [{},{},{}]
最佳答案
尝试
new FileOutputStream(f.getAbsoluteFile(), false)
true参数追加到当前文件,false应该创建一个新文件
关于java - 如何正确创建json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32558794/