/ / El objeto JSON devuelve nulo - java, json

El objeto JSON devuelve nulo - java, json

Tengo un error muy extraño al intentar obtener un número de una API JSON; El objeto parece ser nulo, aunque la URL (y el código) deben ser correctos.

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

He intentado imprimir el objeto JSON, y me da esto:

{}

Aquí está mi código:

    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
}

Respuestas

1 para la respuesta № 1

@Andreas tiene razón, agregue este fragmento de código en su bloque try para convertir el flujo de entrada en una cadena json -

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());