如何使用Jackson将对象添加到现有的JSON文件

3
我该如何使用Jackson将一个对象添加到现有的JSON文件中?
File file = new File("test.json");
if (!file.exists()) {
    file.createNewFile();
}

ObjectMapper mapper = new ObjectMapper();

ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
mapper.writeValue(file, wtf);
2个回答

5
在你的问题中,“append”这个词可以有多种意思/解决方案,具体取决于你把这个词放在哪个上下文中。例如:
1. 简单地将内容追加到文件中,忽略现有的JSON结构。 2. 追加到文件中现有的JSON数组中。
- 在JSON数组尚未关闭时追加到现有的JSON数组中。 - 在JSON数组已经关闭时追加到现有的JSON数组中。 示例#1的解决方案:
// File output: {"name":"Foo","age":20} {"name":"Bar","age":30} {"name":"Baz","age":40}
public static void plainAppendExample() {
    File file = new File("u:\\test.json");
    ObjectMapper mapper = new ObjectMapper();
    try {
        JsonGenerator g = mapper.getFactory().createGenerator(new FileOutputStream(file));

        mapper.writeValue(g, new Person("Foo", 20));
        mapper.writeValue(g, new Person("Bar", 30));
        mapper.writeValue(g, new Person("Baz", 40));
        g.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

每次调用writeValue()方法,都会向文件追加一个简单的JSON对象,但是忽略了之前的JSON结构。

示例#2.1的解决方案:

// File output: [ {"name" : "Foo", "age" : 20}, {"name" : "Bar", "age" : 30}, {"name" : "Baz", "age" : 40} ]
public static void jsonArrayAppendExample2() {
    try {
        File file = new File("u:\\test.json");
        FileWriter fileWriter = new FileWriter(file, true);

        ObjectMapper mapper = new ObjectMapper();

        SequenceWriter seqWriter = mapper.writer().writeValuesAsArray(fileWriter);
        seqWriter.write(new Person("Foo", 20));
        seqWriter.write(new Person("Bar", 30));
        seqWriter.write(new Person("Baz", 40));
        seqWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

每次调用write()方法时,都会将内容追加到文件中的现有JSON数组中,直到调用close()方法为止。

例子2.2的解决方案: 我没有找到解决方案。在这种情况下,解决方案应该通过替换数组结束字符]来修改文件,然后执行追加操作。

或者,如果性能和内存不是问题,您可以将JSON文件重新读取为Java对象,然后添加一个新的JSON对象,然后再次写入文件。

注意: 请注意,我不是Jackson专家,因此不知道我的解决方案是否是最佳解决方案。


我正在尝试找到类似于2.2的东西,并找到了这个链接:https://www.geekyhacker.com/2020/04/07/append-arrays-to-an-existing-json-file-with-jackson/ - andreagalle

1

我不太确定wtf是什么,但是Jackson会为您映射它:

class Wtf {
    String  brand;
    boolean stinks;

    public String getBrand() {
       return brand;
    }
    public boolean getStinks() {
       return stinks;
    }
    public void setBrand(String brand) {
       this.brand = brand;
    }
    public void setStinks(boolean stinks) {
       this.stinks = stinks;
    }
}

// From your code...
ObjectMapper mapper = new ObjectMapper();

// Insert
Wtf wtf = new Wtf();
wtf.setBrand("Noodle");
wtf.setStinks(true);

ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
mapper.writeValue(file, wtf);

这是你的问题吗?

这样做不会覆盖文件吗?而是将wtf对象添加到test.json内部的现有JSON数据中? - Chimp_Town
是的。从这篇文章http://stackoverflow.com/questions/27653044/how-to-append-pojos-in-a-json-file-using-jackson-library得出的解决方案是利用`mapper.writeValueAsString`获得一个字符串,然后将其作为数组附加到文件中。 - jiveturkey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接