Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...