Arraying Arraying - 1 month ago 6
Java Question

JSON Object Returns Null

I have a very strange error when trying to get a number from a JSON API; the object seems to be null, although the URL (and code) should be correct.

org.json.JSONException: JSONObject["success"] not found.


I have tried printing out the JSONObject, and it gives me this:

{}


Here is my code:

try{
String url = "https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint16";
JSONObject jsonObject = new JSONObject(new URL(url).openStream());
String resultType = jsonObject.getString("success");
if(resultType.equalsIgnoreCase("true")){
JSONArray jsonArray = jsonObject.getJSONArray("data");
int number = jsonArray.getInt(0);
//do stuff with number
}
else{
//unsuccessful
}
}
catch(Exception e){
//handle catch
}

Answer

@Andreas is right, add this piece of code in your try block to convert input stream into a json string -

InputStream is = new URL(url).openStream();
int ch;
StringBuilder sb = new StringBuilder();
while((ch = is.read()) != -1)
sb.append((char)ch);            
JSONObject jsonObject = new JSONObject(sb.toString());
Comments