将JsonFile读取到ArrayList

时间:2019-07-01 16:12:58

标签: java

我愿意根据测验创建一些东西。老师为我们提供了QuestionsTest甚至display the quiz的“图形层”的所有接口。

我为Test和Question接口创建了两个类。测试类具有一个Questions对象的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;
}

1 个答案:

答案 0 :(得分:0)

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

据此,我想到了两种可能性:

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

2)您应设置一个变量,例如this.testthis.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);

This website包含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") {
               //...