S. O. Chaos S. O. Chaos - 3 years ago 242
Java Question

Error parsing VALID Json file in Java

I have a JSON file:

{
"dev_status": "test",
"test": {
"id": "0",
"access_key": "xxx",
"image_directory": "D:/test_folder/"
},
"release": {
"id": "1",
"access_key": "xxx",
"image_directory": "/home/imgs/"
}
}


and I'm trying to turn into
org.json.JSONObject
with the following code:

public static void main(String... args) {
URL configURL = this.getClass().getClassLoader().getResource(configPath);
if (configURL == null) {
try {
throw new IOException("Config file with such name wasn't found.");
} catch (IOException e) {
e.printStackTrace();
}
} else {
JSONObject config = new JSONObject(configURL.getFile());
}


But I'm getting exception:

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


So I obviously have a valid JSON object starting with '{' but I still get this error. How do I fix it?

Answer Source

I have used your json in test.json file and used the below snippet

    String myJson = null;
    try {
            myJson = new Scanner(new File("test.json")).useDelimiter("\\Z")
                        .next();

            JSONObject myJsonobject = new JSONObject(myJson);

            System.out.println(myJsonobject.get("dev_status"));
            System.out.println(myJsonobject.get("test"));
        } 
   catch (ParseException e) 
      {
           e.printStackTrace();
      } 
   catch (FileNotFoundException e) 
     {
         e.printStackTrace();
     }

And the output was

test
{"image_directory":"D:\/test_folder\/","access_key":"xxx","id":"0"}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download