1

I am building a quiz application where the user can answer multiple questions by choosing one option out of a, b, c, d. Right now, when the user is entering his answer to a question, the answer is getting stored in an ArrayList but I want it to get stored as values to keys in a JSON object. My JSON file looks like this currently:

[  
  {"Q1":  ""},  
  {"Q2":  ""},  
  {"Q3":  ""},  
  {"Q4":  ""},  
  {"Q5":  ""},  
  {"Q6":  ""},  
  {"Q7":  ""},  
  {"Q8":  ""},  
  {"Q9":  ""},  
  {"Q10":  ""},  
  {"Q11":  ""},  
  {"Q12":  ""},  
  {"Q13":  ""},  
  {"Q14":  ""},  
  {"Q15":  ""}  
]

Here is the code for getting answers from the user:

   public ArrayList<String> askQuestionsOneByOne() {
    QuizQuestions qq = new QuizQuestions();
    Set<Map.Entry<String, String>> entry = qq.entireQuestionsList().entrySet();
    ArrayList<String> userAnswer = new ArrayList<>();
    for (Object o : entry) {
        System.out.println(o);
        String answer = askUser();
        askUserIfHeWantsToQuit();
        userAnswer.add(answer);
    }
    return userAnswer;
}

As the user enters the answer, I want that answer to be stored in the corresponding question value in this file in place of the empty string but I don't know how to do that. I would appreciate guidance on this.

Thanks

4
  • would make it a lot easier if you could tell us how is the data you're getting from the user encoded or share with us the portion of the code that gets the answers from the user Commented Oct 17, 2021 at 17:58
  • I have edited my question and added that! Commented Oct 17, 2021 at 18:00
  • Please write it more clearly. What is input and what is expected output? Commented Oct 17, 2021 at 18:08
  • The input is the user's input to a particular question, one of the strings "a", "b", "c", "d". I want these strings to be added to the json file as values to keys for the corresponding question. For example, if for the first question, the user enters the answer as "a", then in the json file, it will look like this: [ {"Q1": "a"} ] Let me know if you need more clarity! Commented Oct 17, 2021 at 18:10

2 Answers 2

2

You need to use a json library like org.json, create a JSONArray and fill it with JSONObjects, Assuming I understand the structure correctly, what you're referring to as Object o is actually a Map.Entry<String, String> , which you can use to get a key and a value, I believe the key will have the question (Q1, Q2, Q3...) which you can use to add objects into the JSONArray

JSONArray arr = new JSONArray();
    
for (Map.Entry<String, String> o: entry) {
    String answer = askUser();
    
    JSONObject answerObject = new JSONObject();
    answerObject.put(o.getKey(), answer);
    
    arr.put(answerObject);
}

System.out.println(arr.toString(4));

output:

[
    {"Q1": "c"},
    {"Q2": "a"},
    {"Q3": "b"},
    {"Q4": "b"},
    {"Q5": "c"}
]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply! This is exactly what I want except for the fact that I don't want to add answers manually as you have described here. I want them to be added automatically to the corresponding question as the user answers it.
i wouldn't say that's impossible but keep in mind that java sets are unordered so even my answer might produce problems because of order, i need more information about the structure of the questions (what entireQuestionsList() returns)
entireQuestionsList() returns a LinkedHashMap<String, String> where the first string is the question and the second string consists of the 4 answer options to that question.
1

JSON is file format that allow to transfer objects between different programs, even when they use different programming languages. If you really want the solution in such form, you need to use some library that provides JSON service (I recommend GSON from myself). The code from the solution in form you want: Firstly you need to make a class (e.g. Answers):

public class Answers {
    String Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15;

    public void setQ1(String q1) {
        Q1 = q1;
    }

    public void setQ2(String q2) {
        Q2 = q2;
    }

    public void setQ3(String q3) {
        Q3 = q3;
    }

    public void setQ4(String q4) {
        Q4 = q4;
    }

    public void setQ5(String q5) {
        Q5 = q5;
    }

    public void setQ6(String q6) {
        Q6 = q6;
    }

    public void setQ7(String q7) {
        Q7 = q7;
    }

    public void setQ8(String q8) {
        Q8 = q8;
    }

    public void setQ9(String q9) {
        Q9 = q9;
    }

    public void setQ10(String q10) {
        Q10 = q10;
    }

    public void setQ11(String q11) {
        Q11 = q11;
    }

    public void setQ12(String q12) {
        Q12 = q12;
    }

    public void setQ13(String q13) {
        Q13 = q13;
    }

    public void setQ14(String q14) {
        Q14 = q14;
    }

    public void setQ15(String q15) {
        Q15 = q15;
    }
}

Then you need to make an object of class Answers which will handle answers and convert it to JSON (using GSON for example):

Answers answers = new Answers();
    //somehow set the values (maybe by using Scanner.in?)
        answers.setQ1("YES");
        answers.setQ2("YES");
        answers.setQ3("NO");
        answers.setQ4("NO");
        answers.setQ5("dog");
        answers.setQ6("Giraffe");
        answers.setQ7("Gson");
        answers.setQ8("Java");
        answers.setQ9("CSS");
        answers.setQ10("NO");
        answers.setQ11("Maven");
        answers.setQ12("dog");
        answers.setQ13("Elephant");
        answers.setQ14("Gson");
        answers.setQ15("No");
    //using Gson
        String json_file;
        Gson g = new Gson();
        json_file = g.toJson(answers);
    // to file
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("answers.json"));
            writer.write(json_file);

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

.json file:

{
  "Q1": "YES",
  "Q2": "YES",
  "Q3": "NO",
  "Q4": "NO",
  "Q5": "dog",
  "Q6": "Giraffe",
  "Q7": "Gson",
  "Q8": "Java",
  "Q9": "CSS",
  "Q10": "NO",
  "Q11": "Maven",
  "Q12": "dog",
  "Q13": "Elephant",
  "Q14": "Gson",
  "Q15": "No"
}

However, in my opinion the code that satisfy your idea is too complicated and I highly recommend to reconsider it. Maybe it would be better to use Answers class with some informations about the person that plays the quiz and much cleaner String Array of answers instead of different variables for each one. Programmer should always try to find a way to optimize, clean and simplify the solution. As an example:

public class Answers {
    int id;
    String name;
    String surname;
    String[] answer;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public Answers() {
        answer = new String[15];
    }
}

main body:

Answers answers = new Answers();
    //somehow set the values (maybe by using Scanner.in?)
        answers.setId(1);
        answers.setName("John");
        answers.setSurname("Baker");
        answers.answer[0] = "YES";
        answers.answer[1] = "YES";
        answers.answer[2] = "NO";
        answers.answer[3] = "NO";
        answers.answer[4] = "Elephant";
        answers.answer[5] = "Java";
        answers.answer[6] = "Maven";
        answers.answer[7] = "CSS";
        answers.answer[8] = "bash";
        answers.answer[9] = "quiz";
        answers.answer[10] = "dog";
        answers.answer[11] = "coffee";
        answers.answer[12] = "tea";
        answers.answer[13] = "YES";
        answers.answer[14] = "Borneo";
    //using Gson
        String json_file;
        Gson gson = new Gson();
        json_file = gson.toJson(answers);
    // to file
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("answers.json"));
            writer.write(json_file);

output .json:

{
  "id": 1,
  "name": "John",
  "surname": "Baker",
  "answer": [
    "YES",
    "YES",
    "NO",
    "NO",
    "Elephant",
    "Java",
    "Maven",
    "CSS",
    "bash",
    "quiz",
    "dog",
    "coffee",
    "tea",
    "YES",
    "Borneo"
  ]
}

You can add some code for input of answers (I mean to make them be taken from keyboard or what you want), but I redirect to google. Be creative!

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.