简体   繁体   中英

How to Write Json Array to file using jackson

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

    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

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

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

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 jsonDataObject is your actual object(ie object or array) which you want to write in file.

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
} ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM