Reputation: 8699
I am trying to append a class object to the existing json file using java but getting following output:
[{"email_id":"[email protected]","password":"Password ","user_name":"Anubhav Singh"}] {"email_id":"[email protected]","password":"madhav1234", "user_name":"Madhav kumar"}
But the expected output should be:
[{"email_id":"[email protected]", "password":"Password ","user_name":"Anubhav Singh"},{"email_id":"[email protected]","password":"madhav1234","user_name":"Madhav kumar"}]
My code:
FileWriter file = new FileWriter("/home/anubhav55182/NetBeansProjects/Tweetoria/src/java/Signup/data.json",Boolean.TRUE);//output json file
JSONObject obj = new JSONObject();//for json file generation
obj.put("user_name",name);
obj.put("user_id",username);
obj.put("email_id",email);
obj.put("password",pass);
file.write(obj.toJSONString());
file.flush();
Could someone help me to append new object to existing json file using java.
Thanks in advance for your help.
Upvotes: 0
Views: 1756
Reputation: 197
You're currently only adding another JSONObject to the file. The functionality you're looking for requires you to read in the existing file (with email_id: [email protected]) as a JSONArray. From there, you can append the array with your new object.
You'll want to read in the file as an array, put the info to be added into a JSONObject (as you have above) and then add that object to the array.
Here are the Oracle docs for JSONArray: http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html
Upvotes: 2