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
}
JSONObjectconstructor that takes anInputStreamas a parameter.JSONObject(java.lang.Object bean). Since theInputStreamreturned byopenStream()(which you need to close too, or you have a memory leak), and since it has no "bean" getters, you end up with an empty JSON object. In short, you're calling it wrong, i.e. not actually giving it the JSON string.