繁体   English   中英

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

[英]JSONException on trying to get a value from Json to String

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

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

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

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

如果您注意到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键和JSONObject映射作为值,然后您需要从映射值中获取title

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

案例2带有来源

{
"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"
            }
        }
    }
}

因此source可能不会出现在每个响应中,请尝试尝试捕获

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

      //use try catch to get source because you will not get the same response every time

      String source = v.getJSONObject("thumbnail").getString("source");
  });


}

尝试这个...

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

您应该知道页面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");
          }
      }

因此,由于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);
        }

暂无
暂无

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

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