如何使用gson创建一组键值对? [英] How can I use gson to create a set of key value pairs?

查看:305
本文介绍了如何使用gson创建一组键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有这段代码,如何添加它,以便可以从Gson获取JsonObject并将其附加到现有的Json文件中?

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

推荐答案

JSON结构不允许只append在文件末尾添加更多数据.在这种情况下,更适合的是CSV格式.

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.

要解决您的问题,您需要将整个文件读取为JsonObject,添加新的键值"对并将其保存回去.

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

上面的代码显示:

{"jon":"ewemn!32","rick":"923djks"}

这篇关于如何使用gson创建一组键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆