首页 > 解决方案 > 将 JsonFile 读取到 ArrayList

问题描述

我有一个要在测验的线条上创造一些东西的方法。老师给了我们所有的问题测试界面,甚至“图形层”来显示测验

我为 Test 和 Question 接口创建了两个类。测试类具有问题对象的 listArray 以及其他属性。Question 类具有您可以在 JSON 文件中看到的属性(标题、分数、标记等...)。

为了读取 Json 文件,我创建了“loadfromJsonFile”方法,它完美地打印了文件,但我不知道如何将文件中的每个问题对象关联到 arrayList。

json文件:

[
{
    "type": "MultipleChoice",
    "question": {
        "title": "Question 1",
        "score": 4,
        "mark":  5,
        "question_description": "The ability of an object to take on many forms is:",
        "options": [
            "Polymorphism",
            "Encapsulation",
            "Design Patter",
            "Does not Exist"
        ],
        "correct_answer": "Polymorphism"
    }
},

{
    "type": "MultipleChoice",
    "question": {
        "title": "Question 2",
        "score": 4,
        "mark":  5,
        "question_description": "The bundling of data with the methods that operate on that data is:",
        "options": [
            "Polymorphism",
            "Encapsulation",
            "Design Patter",
            "Does not Exist"
        ],
        "correct_answer": "Encapsulation"
    }
},
{
    "type": "YesNo",
    "question": {
        "title": "Question 3",
        "score": 4,
        "mark":  5,
        "question_description": "Object Oriented Programming is exclusive to the JAVA programming language",
        "correct_answer": "no"
    }
},
{
    "type": "Numeric",
    "question": {
        "title": "Question 4",
        "score": 4,
        "mark":  5,
        "question_description": "How many programming languages are taught in Paradigmas de Programação?",
        "correct_answer": "1"
    }
}]

读取 Json 文件的代码:

public boolean loadFromJSONFile(String s) throws TestException {
    String path = "teste_A.json";
    BufferedReader reader = null;

    try{
        reader = new BufferedReader(new FileReader(path));

        JsonStreamParser p = new JsonStreamParser(reader);
        JsonArray arr = (JsonArray) p.next();

        for(int i=0;i<arr.size();i++){
            System.out.println("--------------------------------------Question"+i+"--------------------------------------------");
            JsonElement arrayElement = arr.get(i);
            JsonObject obj = arrayElement.getAsJsonObject();
            String type=obj.get("type").getAsString();
            System.out.println("Type: " + type);
            JsonObject list =obj.get("question").getAsJsonObject();
            String title=list.get("title").getAsString();
            System.out.println("Title: " + title);
            int score=list.get("score").getAsInt();
            System.out.println("Score: " + score);
            int mark=list.get("mark").getAsInt();
            System.out.println("Mark: " + mark);
            String Description=list.get("question_description").getAsString();
            System.out.println("Description: " + Description);
            JsonArray opt = list.getAsJsonArray("options");
            if(opt!=null){
                System.out.println("Options: \n");
                for (int j = 0; j < opt.size(); j++) {
                    JsonPrimitive value = opt.get(j).getAsJsonPrimitive();
                    System.out.print("      Option"+ (j+1) +": "+ value.getAsString()+ " \n");
                }
                System.out.println("\n");
            }

            String CorrectAnswer = list.get("correct_answer").getAsString();
            System.out.println("Correct: " + CorrectAnswer);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }


    return false;
}

标签: java

解决方案


这是我的理解:您可以读取 json 文件并解析内容就好了,但问题是如何将结果传递回调用者而不返回参数本身。从代码片段来看,该行 this.current_question = this.test.getQuestion(this.question_number); 似乎是程序中将查询此 ArrayList 的位置。

由此,我想象了几个可能性:

1)有一种setQuestion(<params>)方法可以在老师提供的代码中调用。

2) 有一个变量,例如this.testor this.questions,您应该设置它。

在任何一种情况下,您都将在for循环中添加每个问题。例如,

for(int i=0;i<arr.size();i++){
            System.out.println("--------------------------------------Question"+i+"--------------------------------------------");
            JsonElement arrayElement = arr.get(i);
            JsonObject obj = arrayElement.getAsJsonObject();
            //add obj via variable assignment
            this.test.Add(obj);
            //or, add obj via set method
            this.test.setQuestion(i, obj); //or whatever parameters are needed :)

编辑:

因为您的 Question 类扩展了 IQuestion,所以您可以将 Question 类的实例强制转换为 IQuestion。另外,Question 类正在使用 Gson 库为您反序列化,这意味着您为自己节省了一些跑腿工作。(耶!)

for(int i=0;i<arr.size();i++){
            //get the whole json array element
            JsonElement arrayElement = arr.get(i);
            //...
            //get question object
            JsonObject list = obj.get("question").getAsJsonObject();
            //cast to IQuestion using the Question class Gson deserializer
            IQuestion q = new Gson().fromJson(list, Question.class);
            //And, add using built in method
            this.test.setQuestion(q);

这个网站有一些 Gson 反序列化的例子,其中一个我在上面用过。

编辑:

向 Question 类添加构造函数后,添加特定类型问题的代码将需要类型转换。

for(int i=0;i<arr.size();i++){
            //get the whole json array element
            JsonElement arrayElement = arr.get(i);
            //...
            //get question object
            JsonObject list = obj.get("question").getAsJsonObject();
            //cast question to correct interface based on question type
            if (type=="Multiple Choice") {
               IQuestionMultipleChoice questionMP = (IQuestionMultipleChoice) new Question(<params>);
               this.test.setQuestion(questionMP);
            } else if(type=="Yes/No") {
               //...

推荐阅读