首页 > 解决方案 > 尝试从 Json 到 String 获取值时出现 JSONException

问题描述

我正在尝试使用下一个 API 链接从 Wikipedia 获取 2 个值:

https://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=pageimages&format=json&pithumbsize=500&utf8

因为它是随机生成的,有时它不会返回我需要的值之一,但我稍后会解决这个问题,目前我在访问 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");

标签: javajson

解决方案


您不能直接从 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");

推荐阅读