Skip to content
Advertisement

Reading a JsonFile to an ArrayList

I have an assingment to create something on the lines of a quiz. The teacher gave us all the interfaces for the Questions and the Test and even the “graphic layer” to display the quiz.

I created two classes for the Test and Question interfaces. The test class has a listArray of Questions objects along with other atributes. The Question class has the atributes you can see in the JSON File(title,score,mark,etc…).

To read the Json file i created the method “loadfromJsonFile”, and it prints the file perfectly but i cant figure out how to associate each question object from the file to the arrayList.

Json File:

[
{
    "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"
    }
}]

Code for reading the Json File:

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;
}

Advertisement

Answer

Here is my understanding: you can read the json file and parse the contents just fine, but the issue is how to pass the results back to the caller without returning the parameter itself. From the code snippets, the line this.current_question = this.test.getQuestion(this.question_number); seems like where this ArrayList will be queried in the program.

From this, I am imagining a couple of possibilites:

1) There is a setQuestion(<params>) method that you could call in the teacher’s provided code.

2) There is a variable such as this.test or this.questions that you should be setting.

In either case, you would add each question inside your for loop. For example,

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 :)

EDIT:

Because your Question class extends IQuestion, you can cast an instance of the Question class to IQuestion. Plus, the Question class is using a Gson library to deserialize for you, which means you saved yourself some legwork. (yay!)

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 has some examples of Gson deserialization, one of which I used up above.

EDIT:

After adding a constructor to the Question class, the code to add a question of specific types will need type casting.

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") {
               //...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement