gpt4 book ai didi

java - JSON 对象返回 Null

转载 作者:行者123 更新时间:2023-12-01 09:18:37 24 4
gpt4 key购买 nike

当我尝试从 JSON API 获取数字时,遇到一个非常奇怪的错误;尽管 URL(和代码)应该是正确的,但该对象似乎为 null。

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 block 中添加这段代码以将输入流转换为 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());

关于java - JSON 对象返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com