javajsonjsonparsersimplejsonjson-simple

Why can't read a .json?


I want to read a .json using library json-simple, my json file is:

{
    "Subjects": {
    "subject1": "MIS",
    "subject2": "DBMS",
    "subject3": "UML"
    }
}

And my code is:

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
            JSONObject jsonObject = (JSONObject)obj;
            JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
            Iterator iterator = subjects.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

I would like to get in console:

subject1: MIS
subject2: DBMS
subject3: UML

But instead of that, I just get the next error:

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
    at project.Main(Main.java:11)

But I searched in internet, and I found that if I change sintaxys of the .json in the next way:

{
    "Subjects": [
    "subject1: MIS",
    "subject2: DBMS",
    "subject3: UML"
    ]
}

I get in console what I want:

subject1: MIS
subject2: DBMS
subject3: UML

And you may think my problem is solved, but not yet, because I want to read the json file in the first way. I hope someone can help me. Thanks in advance.


Solution

  • The first example shows a Subjects key containing a single object with several properties (subject1, subject2, etc).
    Consider those properties like the member variables of a class. In order to let you better understand if the class is Person those variables could be name and surname.

    What you try to achieve in your code is extracting a JSONArray from the JSON you are providing. Going back to the example for Person the array could be - sorry for the silly example - an Array containing phone numbers. So what you are expecting is that one of the member properties of the class is an array.

    This is not possible in the first example because the first example does not contain a json array.

    This line extracts the whole json object:
    JSONObject jsonObject = (JSONObject)obj;

    This one tries to get an array out but no array is there in the first example:
    JSONArray subjects = (JSONArray)jsonObject.get("Subjects");