How to write Json Array to a file using jackson

I created a Json file where I wanted to write a java write object as an Array element. I use 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 definitely want .it creates data like

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

I just need to create a Json array, where I add a java object, the data should look like

 [{ "storyTitle" : "ttt", "storyBody" : "tttt", "storyAuthor" : "tttt" } ,{ "storyTitle" : "a", "storyBody" : "a", "storyAuthor" : "a" }] 
+5
source share
1 answer

Jackson provides built-in methods for writing JSON data to a JSON file. you can use this line of code 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 (like an object or an array) that you want to write to the file.

+4
source

Source: https://habr.com/ru/post/1239863/


All Articles