尝试从Json获取值到String时出现JSONException

时间:2019-01-19 17:19:00

标签: java json

我正尝试通过下一个API链接从Wikipedia获取2个值:

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

因为它是随机生成的,所以有时它不返回我需要的值之一,但是我稍后会解决,目前我在访问Json中需要的两个值“ title”时遇到了问题和“来源”

返回的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");

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

如果您注意到JSON是随机生成的,但具有特定格式

案例1

{
"batchcomplete": "",
"continue": {
    "grncontinue": "0.720220803439|0.720221273467|12887566|0",
    "continue": "grncontinue||"
},
"query": {
    "pages": {
        "4897672": {
            "pageid": 4897672,
            "ns": 0,
            "title": "New Hope, Sunnyvale, Texas"
        }
    }
  }
}

querypages一直存在,并且密钥总是在页面中随机生成,因此它是Map<String, JSONObject>密钥和String的{​​{1}}映射作为值,那么您需要从地图值中获取JSONObject

title

案例2 带有来源

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);

  Map<String,JSONObject> map =  (Map<String, JSONObject>) incomingJSON.getJSONObject("query").getJSONObject("pages");

  map.forEach((k,v)->System.out.println(" The key is : "+k+" the title is : "+v.getString("title")));

因此,{ "batchcomplete": "", "continue": { "grncontinue": "0.165621850014|0.165622038679|37982311|0", "continue": "grncontinue||" }, "query": { "pages": { "57529788": { "pageid": 57529788, "ns": 0, "title": "Model Store", "thumbnail": { "source": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/23/Australia_New_South_Wales_relief_location_map.png/500px-Australia_New_South_Wales_relief_location_map.png", "width": 500, "height": 443 }, "pageimage": "Australia_New_South_Wales_relief_location_map.png" } } } } 可能不会出现在每个响应中,请尝试使用try catch

source

答案 2 :(得分:0)

尝试一下...

JSONObject incomingJSON = new JSONObject(responseSB);

JSONObject TitleObjects = incomingJSON.getJSONObject("query");
JSONObject j_Objects_01 = TitleObjects.getJSONObject("pages");
JSONObject j_Objects_02 = j_Objects_01.getJSONObject("38690716");

String mTitle = j_Objects_02.getString("title");
JSONObject j_Objects_03 = j_Objects_02.getJSONObject("thumbnail");
String mUrl = j_Objects_03.getString("source");

答案 3 :(得分:0)

您应该知道页面ID将会更改,并且缩略图是可选的。

      // new code
      JSONObject incomingJSON = new JSONObject(responseSB);
      JSONObject pages = incomingJSON.getJSONObject("query").getJSONObject("pages");
      Iterator<String> it = pages.keys();

      while(it.hasNext()) {
          JSONObject page = pages.getJSONObject(it.next());
          String mTitle= page.getString("title");
          if(page.keySet().contains("thumbnail")) {
              String mUrl= page.getJSONObject("thumbnail").getString("source");
          }
      }

答案 4 :(得分:0)

因此,由于ID一直在变化,因此我决定采用另一种方法。 我使用了以下代码:

    Pattern p = Pattern.compile("\"source\":\"(.*?)\",\"width");
    Matcher m = p.matcher(responseSB);

        if (m.find()) {
            url = m.group(1);
        }

        p = Pattern.compile("\"title\":(.*?)\",\"thumbnail");
        m = p.matcher(responseSB);

        if (m.find()) {
            description = m.group(1);
        }