如何使用 jackson 将 Json 数组写入文件

2022-09-02 03:22:14

我创建了一个Json文件,我想将写入java对象作为数组元素。我使用杰克逊。

    try{
           String json;
           String phyPath = request.getSession().getServletContext().getRealPath("/");
           String filepath = phyPath + "resources/" + "data.json";
           File file = new File(filepath);
           if (!file.exists()) {
               System.out.println("pai nai");
               file.createNewFile();               
           }  
           json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(story);
           Files.write(new File(filepath).toPath(), Arrays.asList(json), StandardOpenOption.APPEND);    
    } 

这不是我真正想要的.它创建的数据像

{
  "storyTitle" : "ttt",
  "storyBody" : "tttt",
  "storyAuthor" : "tttt"
}
{
  "storyTitle" : "a",
  "storyBody" : "a",
  "storyAuthor" : "a"
}

我只需要创建一个Json数组,其中我添加了java对象,数据应该是这样的

[{
  "storyTitle" : "ttt",
  "storyBody" : "tttt",
  "storyAuthor" : "tttt"
}
,{
  "storyTitle" : "a",
  "storyBody" : "a",
  "storyAuthor" : "a"
}]

答案 1

Jackson提供了用于将JSON数据写入JSON文件的内置方法。你可以用这些代码行来做这个

ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
writer.writeValue(new File("D:/cp/dataTwo.json"), jsonDataObject);
//new file(path of your file) 

并且是您要写入文件的实际对象(即对象或数组)。jsonDataObject


答案 2

这可以通过使用数组来完成:

    ObjectMapper objectMapper = new ObjectMapper();

    Student student = new Student();

    student.setActive(false);
    student.setFirstName("Kir");
    student.setId(123);
    student.setLastName("Ch");

    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    try {
        List<Student> listOfStudents = new ArrayList<>();
        listOfStudents.add(student);
        listOfStudents.add(student);
        objectMapper.writeValue(new File("d:/temp/output.json"), listOfStudents);
    } catch (IOException e) {
        e.printStackTrace();
    }

结果将如下所示:

[ {
  "id" : 123,
  "firstName" : "Kir",
  "lastName" : "Ch",
  "active" : false,
  "address" : null,
  "languages" : null
}, {
  "id" : 123,
  "firstName" : "Kir",
  "lastName" : "Ch",
  "active" : false,
  "address" : null,
  "languages" : null
} ]