简体   繁体   English

将值写入多个 JSON 对象

[英]Writing of values to multiple JSON objects

I am building a quiz application where the user can answer multiple questions by choosing one option out of a, b, c, d.我正在构建一个测验应用程序,用户可以通过从 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.现在,当用户输入他对问题的答案时,答案被存储在一个 ArrayList 中,但我希望它被存储为 JSON 对象中键的值。 My JSON file looks like this currently:我的 JSON 文件目前看起来像这样:

[  
  {"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谢谢

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你需要使用像org.json这样的 json 库,创建一个 JSONArray 并用 JSONObjects 填充它,假设我正确理解了结构,你所指的Object o实际上是一个Map.Entry<String, String> ,它你可以用来获取一个键和一个值,我相信这个键会有问题(Q1、Q2、Q3 ...),你可以用它来将对象添加到 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"}
]

JSON is file format that allow to transfer objects between different programs, even when they use different programming languages. JSON 是允许在不同程序之间传输对象的文件格式,即使它们使用不同的编程语言。 If you really want the solution in such form, you need to use some library that provides JSON service (I recommend GSON from myself).如果你真的想要这种形式的解决方案,你需要使用一些提供 JSON 服务的库(我自己推荐 GSON)。 The code from the solution in form you want: Firstly you need to make a class (eg 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 类的对象,该对象将处理答案并将其转换为 JSON(例如使用 GSON):

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: .json 文件:

{
  "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.也许最好使用 Answers 类,其中包含有关进行测验的人的一些信息和更清晰的答案字符串数组,而不是每个答案的不同变量。 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:输出.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.您可以添加一些用于输入答案的代码(我的意思是让它们从键盘或您想要的东西中获取),但我重定向到 google。 Be creative!要有创意!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM