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"
}]
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.
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.
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.
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
} ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With