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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34605832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:50:07  来源:igfitidea点击:

How to Write Json Array to file using Hymanson

javajsonHymanson

提问by Sayem

I created a Json file where i wanted to write write java object as Array element. Im using Hymanson.

我创建了一个 Json 文件,我想在其中编写 java 对象作为 Array 元素。我正在使用Hyman逊。

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

This is not what i exactly want .it creates data like

这不是我真正想要的。它创建的数据如下

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

I just need to create a Array of Json where i add java object, data should be like this

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

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

回答by Jitender

Hymanson provide inbuilt methods for writing JSON data to JSON file. you can use these sort of code line for this

Hymanson 提供了将 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) 

and jsonDataObjectis your actual object(i.e object or array) which you want to write in file.

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

回答by Kirill Ch

It can be done by using arrays:

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

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

The result will be like this:

结果将是这样的:

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