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
}
asked Oct 30, 2016 at 15:34
Arraying
1792 gold badges3 silver badges11 bronze badges
1 Answer 1
@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());
answered Oct 30, 2016 at 16:06
Derrick
4,5695 gold badges42 silver badges54 bronze badges
Sign up to request clarification or add additional context in comments.
lang-java
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.