I have a task, in one part of which I have to get a message from the site about the possible delay of the train.

String adress2 = "http://api.sl.se/api2/deviations.json?key=d3fa46ed7ddf4af7a5ef18fd353f0088&transportMode=metro&lineNumber=10&siteId=9161&fromDate=2018-05-24&toDate=2018-05-25"; try { URL v = new URL(adress2); URLConnection connection = v.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int code = httpConnection.getResponseCode(); if(code != HttpURLConnection.HTTP_OK){ throw new MalformedURLException(); } InputStream instream = connection.getInputStream(); Scanner in = new Scanner(instream); while(in.hasNextLine()){ String input = in.nextLine(); JSONObject result = new JSONObject(input); //Проблема на строке ниже JSONObject response = result.getJSONObject("ResponseData"); String message = response.getString("Details"); } } catch (MalformedURLException ex) { System.out.println("Felaktig adress"); } catch (IOException ex) { System.out.println("Filen kunde inte läsas in"); } 

ResponseData is of type deviations, Details is of type string. I get an error:

Exception in thread "main" org.json.JSONException: JSONObject ["ResponseData"] is not a JSONObject.

How to solve this problem?

1 answer 1

 if (!result.isNull("ResponseData")) JSONObject response = result.getJSONObject("ResponseData"); else System.err.println("Error: " + result.getString("Message"));