繁体   English   中英

JSON对象返回Null

[英]JSON Object Returns Null

尝试从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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM