如何在 json 文件中列出 JsonArray?<java>



我试图制作一个被禁止的用户列表,并将其存储在json文件中,我制作了一个JsonArray,其中包括:

JsonObject json = new JsonObject();
json.addProperty("user", user);
json.addProperty("reason", reason);
json.addProperty("unbanned", Unbanned);
json.addProperty("by", who);
json.addProperty("bannedat", System.currentTimeMillis());

我现在想把这个和其他信息一起添加到一个名为";bans.json";但我不确定该怎么做,我该怎么做?

您可以使用PrintWriter

String jsonString = json.toString(); //Creates a String of the contents ready to be written to a file
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter("D:\File.json"));
pw.write(jsonString);
} catch (Exception e) {
System.out.println(e.toString());
}

使用您的代码:-

JsonObject json = new JsonObject();
json.addProperty("user", user);
json.addProperty("reason", reason);
json.addProperty("unbanned", Unbanned);
json.addProperty("by", who);
json.addProperty("bannedat", System.currentTimeMillis());
//The writing to file part
String jsonString = json.toString();
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileWriter("D:\File.json"));
pw.write(jsonString);
} catch (Exception e) {
System.out.println(e.toString());
}

最新更新