JSONObject issue A JSONObject text must begin with '{' at

1.1k views Asked by At

So Im trying to use this json file, but when I try to parse it with JSONobject it gives me the error. I tried finding similar issues but it seemed that ppl didnt have the same thing.

The code produce this error msg

Exception in thread "main" org.json.JSONException: 
        A JSONObject text must begin with '{' at 1 [character 2 line 1]

Java:

public void readSubjects(String filename){
    obj =new JSONObject(filename.trim());
    objArr=obj.getJSONArray("subjects".trim());
    String tmpName;
    String tmpRealName;
    for(int i=0;i<objArr.length();i++){
        tmpName=objArr.getJSONObject(i).getString("subject_code");
        tmpRealName=objArr.getJSONObject(i).getString("name");
        System.out.println(tmpName + " " + tmpRealName);
    }
}

JSON-file:

{
    "teachers": [
        {
            "name": [
                "Peremann"
            ],
            "age": 22,
            "subject": [
                "pgr200"
            ],
            "availability": true,
            "contact_info": ""
        },
        {
            "name": "Jarand",
            "age": 23,
            "subject": "root"
        }
    ],
    "subjects": [
        {
            "subject_code": "pgr200",
            "name": "Avansert Javaprogrammering",
            "campus_priority": "Fjerdingen",
            "educationForm": "",
            "subjectProgram": "",
            "duration": "X",
            "amountOfHours": "",
            "amountOfStudents": 12
        }
    ],
    "studentGroups": [
        {
            "students": []
        }
    ],
    "rooms": [
        {
            "room_code": "F11",
            "fasilitetsstoette": "test",
            "max-capasity": 50,
            "room-size": "X"
        }
    ]}
2

There are 2 answers

0
Luciano van der Veekens On

This line

obj =new JSONObject(filename.trim());

is incorrect. The constructor of JSONObject expects an actual JSON string, not the name of a file.

First read the content of the file and then pass it along to JSONObject's constructor.

String content = new String(Files.readAllBytes(Paths.get("example.json")));
obj = new JSONObject(content);
0
Laura Fagan On

I checked Samebug for you to see if any of our users have had a simular issue. They've come back with the following recommendations.

The json is invalid or you try to map to a different model

Replace single quotes (') to double ones ("). You should use double quotes in JSON.

I also found a Github comment that may be useful.