Home > Mobile >  How would i make a list of JsonArrays in a json file? <java>
How would i make a list of JsonArrays in a json file? <java>

Time:08-06

Im trying to make a list of users that are banned and storing it with a json file, i make a JsonArray with this:

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());

I would now like to add this with the other info into a file called "bans.json" but i am unsure how to do so, How would i go about doing this?

CodePudding user response:

You can use a 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());
    }

With your code:-

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());
    }
  • Related