Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write Json Array to file using jackson

Tags:

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"
}]
like image 635
Sayem Avatar asked Jan 05 '16 06:01

Sayem


People also ask

How does Jackson read JSON array?

Reading JSON from a File Thankfully, Jackson makes this task as easy as the last one, we just provide the File to the readValue() method: final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList.

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


2 Answers

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(i.e object or array) which you want to write in file.

like image 70
Jitender Avatar answered Sep 22 '22 03:09

Jitender


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
} ]
like image 21
Kirill Ch Avatar answered Sep 18 '22 03:09

Kirill Ch