java - 尝试从 Json 到 String 获取值时出现 JSONException
问题描述
我正在尝试使用下一个 API 链接从 Wikipedia 获取 2 个值:
因为它是随机生成的,有时它不会返回我需要的值之一,但我稍后会解决这个问题,目前我在访问 Json 中需要的两个值时遇到问题,“标题”和“源” "
返回的 Json 是这样的:
{"batchcomplete":"","continue":{"grncontinue":"0.360395277951|0.360395626487|10429617|0","continue":"grncontinue||"},"query":{"pages":{"38690716":{"pageid":38690716,"ns":0,"title":"Alaine Chartrand","thumbnail":{"source":"https://upload.wikimedia.org/wikipedia/commons/d/d4/Alaine_Chartrand.jpg","width":267,"height":400},"pageimage":"Alaine_Chartrand.jpg"}}}}
这是代码,任何人都可以弄清楚它为什么会出现 JSONException 吗?
String API = "https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8";
//open connection with wikipedia.
HttpURLConnection httpcon = (HttpURLConnection) new URL(API).openConnection();
//read all the input from wikipedia.
BufferedReader in = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
String responseSB = in.lines().collect(Collectors.joining());
in.close();
JSONObject incomingJSON = new JSONObject(responseSB);
//crashes here
String mTitle = incomingJSON.getString("title");
String mUrl = incomingJSON.getString("source");
解决方案
您不能直接从 JSON 响应中获取标题和来源,因为它必须包含多个内部对象。下面是阅读标题和来源的代码快照。
// new code
JSONObject incomingJSON = new JSONObject(responseSB);
JSONObject innerObject = incomingJSON.getJsonObject("query").getJsonObject("pages").getJsonObject("38690716");
String mTitle= innerObject.getString("title");
String mUrl= innerObject.getJsonObject("thumbnail").getString("source");
//crashes here
String mTitle = incomingJSON.getString("title");
String mUrl = incomingJSON.getString("source");
推荐阅读
- linux - 使用 xargs 备份文件的 Bash 脚本
- python - 如何让 Pycharm 的调试器输出更饱满?
- android - 如何在 Kotlin 中只运行一次代码?
- ansible - 运行带有标签的剧本时,Ansible 注册变量为空
- docker - 运行 dockerd.exe 启动 Docker 守护进程
- android - Android kotlin:我已从 url 成功检索数据,我想将这些数据存储到房间数据库类别中
- rust - Rust Cargo 为特定 CPU 构建和交叉编译
- rust - Rust 中将函数转换为 trait 的机制是什么?
- mysql - Mysql select data with sub-select from one table about user tracking:先下降,同月完成
- oracle-apex - 如何更新表中的 APEX_ITEM.TEXT