Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

java - How can I use gson to create a set of key value pairs?

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));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...