how to add new data to existing json file in java

588 Views Asked by At

i'm trying to add new data to existing json file that named question.json but it's not working! it create a new file, can someone help me please!

mycode: i'm using json-simple1.1

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class Main {
    
    public static void writeToJson() {
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("question", "q3");
          ArrayList<String>anss = new ArrayList<>();
          anss.add("a1");
          anss.add("a2");
          anss.add("a3");
          anss.add("a4");
          JSONArray arr = new JSONArray();
          
          arr.add(anss.get(0));
          arr.add(anss.get(1));
          arr.add(anss.get(2));
          arr.add(anss.get(3));
          jsonObject.put("answers",arr);
          
          jsonObject.put("correct_ans", "2");
          
          jsonObject.put("level", "2");
          
          jsonObject.put("team", "animal");
          
          try {
              FileWriter file = new FileWriter("json/quetion.json");
              file.write(jsonObject.toJSONString());
              file.close();
           } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
           }
          

    }
    
    public static void main(String[]args) {
        writeToJson();
    }
}

{
    "questions":[
        {
            "question": "q1",
            "answers": [
                "answer1",
                "answer2",
                "answer3",
                "answer4"
            ],
            "correct_ans": "2",
            "level": "1",
            "team": "animal"
        },
        {
            "question": "q2",
            "answers": [
                "answer1",
                "answer2",
                "answer3",
                "answer4"
            ],
            "correct_ans": "1",
            "level": "2",
            "team": "animal"
        }
    ]
}

this is the json file i want to add what i wrote in the code to this json file but i failed! i need someone to tell me how can i add a new json object like {"question" : "q2" ...} without changing the format of the json file or creating a new json file.

1

There are 1 best solutions below

0
Alexander Ivanchenko On

org.json.simple

The structure of your JSON has more levels of nesting than can be observed in your code therefore your result doesn't match.

That's what you have in the JSON:

JSONObject { field : JSONArray [ JSONObject { field : value, field : JSONArray, ... }

I.e. JSONObject which contains a JSONArray which might contain several JSONObjects which in turn contain a JSONArray.

That's how it can be translated into the code (to avoid redundancy logic which for creating a nested JSONObject was extracted into a separate method):

JSONObject root = new JSONObject();
JSONArray questions = new JSONArray();
        
JSONObject question1 = createQuestion(
    "q1", "2", "1", "animal",
    "answer1", "answer2", "answer3", "answer4"
);
JSONObject question2 = createQuestion(
    "q2", "1", "2", "animal",
    "answer1", "answer2", "answer3", "answer4"
);
        
Collections.addAll(questions, question1, question2);
root.put("questions", questions);
public static JSONObject createQuestion(String questionId,
                                        String correctAnswer,
                                        String level, String team,
                                        String... answers) {

    JSONObject question = new JSONObject();
    question.put("question", questionId);
    
    JSONArray answersArray = new JSONArray();
    Collections.addAll(answersArray, answers);
    
    question.put("answers", answersArray);
    question.put("correct_ans", correctAnswer);
    question.put("level", level);
    question.put("team", team);
    
    return question;
}

That's it.

There's a lot of low-level logic which you can eliminate if you would choose a more mature tool for parsing JSON like Jackson, Gson.

Jackson

Here's an example using Jackson library.

Firstly, let's create two POJO: one representing a single question and another wrapping a list of question. For convince, and also in order to avoid posting boilerplate code, I would use Lombock's.

Question class:

@Builder
@AllArgsConstructor
@Getter
public static class Question {
    private String questionId;
    private List<String> answers;
    private String correctAnswer;
    private String level;
    private String team;
}

Questions class:

@AllArgsConstructor
@Getter
public static class Questions {
    private List<Question> questions;
}

Here's how such objects can be serialized:

Question question3 = Question.builder()
    .questionId("q1")
    .answers(List.of("answer1", "answer2", "answer3", "answer4"))
    .correctAnswer("2")
    .level("1")
    .team("animal")
    .build();
        
Question question4 = Question.builder()
    .questionId("q2")
    .answers(List.of("answer1", "answer2", "answer3", "answer4"))
    .correctAnswer("1")
    .level("2")
    .team("animal")
    .build();
        
Questions questions1 = new Questions(List.of(question3, question4));
        
ObjectMapper mapper = new ObjectMapper();
String json1 = mapper
    .writerWithDefaultPrettyPrinter()
    .writeValueAsString(questions1);
        
System.out.println(json1);

Output:

{
  "questions" : [ {
    "questionId" : "q1",
    "answers" : [ "answer1", "answer2", "answer3", "answer4" ],
    "correctAnswer" : "2",
    "level" : "1",
    "team" : "animal"
  }, {
    "questionId" : "q2",
    "answers" : [ "answer1", "answer2", "answer3", "answer4" ],
    "correctAnswer" : "1",
    "level" : "2",
    "team" : "animal"
  } ]
}