1

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
    }
9
  • Which JSON library are you using? I'm asking because I can't seem to find a library with a JSONObject constructor that takes an InputStream as a parameter. Commented Oct 30, 2016 at 15:38
  • @Andreas Quite honestly I'm not too sure, but the imports I am using are import org.json.JSONArray; import org.json.JSONObject; Commented Oct 30, 2016 at 15:39
  • @Arraying No additional Libraries? Are these JDK classes? Seems wierd to me Commented Oct 30, 2016 at 15:41
  • Seems you're calling this constructor: JSONObject(java.lang.Object bean). Since the InputStream returned by openStream() (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. Commented Oct 30, 2016 at 15:42
  • @n247s Well I haven't manually added anything, it would seem as if they are JDK classes, but I do have Apache Commons added to my dependencies. Commented Oct 30, 2016 at 15:42

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

3 Comments

I've used the following yet it still gives me the same error:
make sure to pass sb.toString() in your JsonObject constructor
Still doesn't work, I even copied and pasted the code, still errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.