如何正确创建 json 文件
How to create json file correctly
所以我无法正确创建 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 文件(用于创建简单的登录)我收到类似 "unexcpected token [[]"
的错误,据我所知,这是因为超过 1 个 json 对象一个文件。
所以我的问题是:如何以我可以通过/例如 [{},{}, {}]
尝试
new FileOutputStream(f.getAbsoluteFile(), false)
true 参数追加到当前文件,false 应该创建一个新的
您的代码的输出应该是一个空数组,因为您从未向该数组添加元素。
您创建一个新数组并对其进行迭代。但是一个新数组没有元素,因此里面的代码
永远不会执行循环。除此之外,您只想添加一个新用户一次,因此您不需要循环。
您应该先读取文件,然后将新用户添加到其中并写回。我为您创建了一个简单的示例。
我以前没有使用过 GSON,所以我确信有更好的方法可以做到这一点,但它仍然有效。
我使用了 try-with-resource 特性和 Java 7 的新 IO API,并没有进一步处理异常。所以如果你想处理异常
在方法内部相应地更改代码。我没有创建文件结构,所以你也应该自己做。
public static void writeUserBD(final String name, final String surname, final int age) throws IOException {
final Path jsonFile = Paths.get("Test/TestUser.json");
final JsonArray users = new JsonArray();
// Read all existing users
if (Files.isRegularFile(jsonFile)) {
try (final JsonReader r = new JsonReader(Files.newBufferedReader(jsonFile))) {
r.beginArray();
while (r.hasNext()) {
final JsonObject user = new JsonObject();
r.beginObject();
r.nextName();
user.addProperty("name", r.nextString());
r.nextName();
user.addProperty("surname", r.nextString());
r.nextName();
user.addProperty("age", r.nextInt());
r.endObject();
users.add(user);
}
r.endArray();
}
}
// Create the new user
final JsonObject user = new JsonObject();
user.addProperty("name", name);
user.addProperty("surname", surname);
user.addProperty("age", age);
users.add(user);
// Write all users
try (final BufferedWriter w =
Files.newBufferedWriter(jsonFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
w.write(users.toString());
}
}
所以我无法正确创建 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 文件(用于创建简单的登录)我收到类似 "unexcpected token [[]"
的错误,据我所知,这是因为超过 1 个 json 对象一个文件。
所以我的问题是:如何以我可以通过/例如 [{},{}, {}]
尝试
new FileOutputStream(f.getAbsoluteFile(), false)
true 参数追加到当前文件,false 应该创建一个新的
您的代码的输出应该是一个空数组,因为您从未向该数组添加元素。 您创建一个新数组并对其进行迭代。但是一个新数组没有元素,因此里面的代码 永远不会执行循环。除此之外,您只想添加一个新用户一次,因此您不需要循环。
您应该先读取文件,然后将新用户添加到其中并写回。我为您创建了一个简单的示例。 我以前没有使用过 GSON,所以我确信有更好的方法可以做到这一点,但它仍然有效。 我使用了 try-with-resource 特性和 Java 7 的新 IO API,并没有进一步处理异常。所以如果你想处理异常 在方法内部相应地更改代码。我没有创建文件结构,所以你也应该自己做。
public static void writeUserBD(final String name, final String surname, final int age) throws IOException {
final Path jsonFile = Paths.get("Test/TestUser.json");
final JsonArray users = new JsonArray();
// Read all existing users
if (Files.isRegularFile(jsonFile)) {
try (final JsonReader r = new JsonReader(Files.newBufferedReader(jsonFile))) {
r.beginArray();
while (r.hasNext()) {
final JsonObject user = new JsonObject();
r.beginObject();
r.nextName();
user.addProperty("name", r.nextString());
r.nextName();
user.addProperty("surname", r.nextString());
r.nextName();
user.addProperty("age", r.nextInt());
r.endObject();
users.add(user);
}
r.endArray();
}
}
// Create the new user
final JsonObject user = new JsonObject();
user.addProperty("name", name);
user.addProperty("surname", surname);
user.addProperty("age", age);
users.add(user);
// Write all users
try (final BufferedWriter w =
Files.newBufferedWriter(jsonFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
w.write(users.toString());
}
}