1

I currently have this code, how can I add to it so I can get a JsonObject from Gson to append it to an existing Json file?

private static void writeFile(File f, String w_username, String w_password) throws IOException{
    Gson gson = new Gson();
    JsonWriter writer = new JsonWriter(new FileWriter(f));
}
  • Are you asking for [Java FileWriter with append mode](https://stackoverflow.com/q/1225146)? – Pshemo Nov 21 '19 at 12:39
  • @Pshemo I'm looking for ways to create a json object and append it to an existing .json file using the Gson library. –  Nov 21 '19 at 12:45
  • @Pshemo Mainly actually just wanting to know how I can create a JsonObject with a Key-Value pair. –  Nov 21 '19 at 12:47
  • I am still not sure what you mean by "...get a JsonObject from Gson". To create JsonObject all you need is `new JsonObject();` Then you can add to it string key/value pairs via `object.addProperty("key", "value");` or something like `object.add("key", otherObject)` (depending on what you want to add). We already have question about it: [Creating GSON Object](https://stackoverflow.com/q/4683856) – Pshemo Nov 21 '19 at 12:53
  • @Pshemo but object.add() only works with JsonElements on the "value" property –  Nov 21 '19 at 12:58
  • Please visit documentation of [JsonObject](https://www.javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/com/google/gson/JsonObject.html). You will find there other methods for other type of data. Notice that `addProperty` has many overloaded versions. – Pshemo Nov 21 '19 at 13:05
  • Welcome to Stack Overflow! Thank you for your question. You're more likely to get a response if you detail what steps you took to try to find a solution. Please see the Stack Overflow Question Guide: https://stackoverflow.com/help/how-to-ask – jeffhale Nov 21 '19 at 13:58

1 Answers1

0

JSON structure does not allow just to append more data at the end of the file. In this case more suitable could be CSV format.

To solve your problem you need to read the whole file as JsonObject, add new "key-value" pair and save it back.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Objects;

public class GsonApp {

    public static void main(String[] args) throws IOException {
        File store = Files.createTempFile("store", "json").toFile();

        // Add two users
        JsonFileAppender jsonFileAppender = new JsonFileAppender();
        jsonFileAppender.appendToObject(store, "jon", "ewemn!32");
        jsonFileAppender.appendToObject(store, "rick", "923djks");

        // Print whole file
        System.out.println(String.join("", Files.readAllLines(store.toPath())));
    }
}

class JsonFileAppender {
    private final Gson gson;

    public JsonFileAppender() {
        this.gson = new GsonBuilder().create();
    }

    public void appendToObject(File jsonFile, String username, String password) throws IOException {
        Objects.requireNonNull(jsonFile);
        Objects.requireNonNull(username);
        Objects.requireNonNull(password);
        if (jsonFile.isDirectory()) {
            throw new IllegalArgumentException("File can not be a directory!");
        }

        JsonObject node = readOrCreateNew(jsonFile);
        node.addProperty(username, password);

        writeToFile(jsonFile, node);
    }

    private JsonObject readOrCreateNew(File jsonFile) throws IOException {
        if (jsonFile.exists() && jsonFile.length() > 0) {
            try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
                return gson.fromJson(reader, JsonObject.class);
            }
        }

        return new JsonObject();
    }

    private void writeToFile(File jsonFile, JsonObject node) throws IOException {
        try (FileWriter writer = new FileWriter(jsonFile)) {
            gson.toJson(node, writer);
        }
    }
}

Above code prints:

{"jon":"ewemn!32","rick":"923djks"}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
  • 1
    Similar problem with `Jackson`: [How to append to JSON with Java and Jackson](https://stackoverflow.com/questions/58888004/how-to-append-to-json-with-java-and-jackson) – Michał Ziober Nov 21 '19 at 22:08
  • Also why do you assign the name "node" to the JsonObject? –  Nov 22 '19 at 04:11
  • 1
    @Raphael, `JSON` payload can be represented by tree, and elements in a [tree](https://www.baeldung.com/java-binary-tree) can be named nodes. Also you can name it as `root` or `jsonNode`. In `Jackson` library an abstract class for different types of nodes is `JsonNode`. – Michał Ziober Nov 22 '19 at 07:30