0

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.

3
  • you get the above mentioned result, because you do not add to the JSONObject which is represented by the file, but you write to the file directly - essentially appending your object to the file. If you want to change that, first you have to parse your File as an JSONArray and then append your JSONObject to it and then write the Array.(you wanna clear the file beforehand, otherwise you'll be appending again) Commented Mar 24, 2017 at 14:05
  • you should read the file first, parse the json array from it and then append this object to the parsed array. Then rewrite the file. Commented Mar 24, 2017 at 14:06
  • That won't work by design. You cannot append a saved 'User' to an existing User, which is not saved withint a List. Commented Mar 24, 2017 at 14:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.