如何使用jackson库将pojos附加到json文件中 [英] how to append pojos in a json file using jackson library

查看:132
本文介绍了如何使用jackson库将pojos附加到json文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jackson库的新手。我已经定期在json文件中写入数据。我所经历的所有当前教程都会覆盖该文件。

I'm new to jackson library.I've got data to write in a json file periodically.All the current tutorial that I've gone through overwrites the file.

推荐答案

我会使用杰克逊图书馆来处理JSON 。类 ObjectMapper 可以将POJO:s转换为JSON,反之亦然。除此之外,我将使用 java.nio.file.Files 类来处理文件编写,如下例所示。

I would use the Jackson library for dealing with JSON. The class ObjectMapper can convert POJO:s to JSON and vice versa. In addition to that I would use the java.nio.file.Files class to handle the file writing as in the example below.

// First, define some POJO
public static class Pojo {
    private final String content;

    @JsonCreator
    public Pojo(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

// This test simply illustrates file writing of JSON objects
@Test
public void testAppendToFile() throws IOException {
    // The ObjectMapper is used to convert between Pojos and JSON (and vice versa)
    final ObjectMapper mapper = new ObjectMapper();

    // Convert a Pojo to JSON
    final String json1 = mapper.writeValueAsString(new Pojo("This is the content #1"));

    // Write it to the file myfile.json. 
    // The first time the file is created and the content is NOT appended
    Files.write(new File("myfile.json").toPath(), Arrays.asList(json1), StandardOpenOption.CREATE);

    // Convert another Pojo to JSON
    final String json2 = mapper.writeValueAsString(new Pojo("This is the content #2"));

    // Write to the file again.
    // The second time the content is appended (due to StandardOpenOption.APPEND)
    Files.write(new File("myfile.json").toPath(), Arrays.asList(json2), StandardOpenOption.APPEND);

    // Read the file and verify that there are 2 lines
    final List<String> lines = Files.readAllLines(new File("myfile.json").toPath());
    Assert.assertEquals(2, lines.size());
}

这篇关于如何使用jackson库将pojos附加到json文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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