尝试从JSON API获取数字时遇到一个非常奇怪的错误;尽管URL(和代码)应该正确,但该对象似乎为空。
org.json.JSONException: JSONObject["success"] not found.
我尝试打印出JSONObject,它给了我这个:
{}
这是我的代码:
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
}
最佳答案
@Andreas是正确的,在您的try块中添加这段代码,以将输入流转换为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());