大家好,我如何解析维基百科的描述,我不需要标题或内容我只需要维基页面的简短描述。所以我要解析,但是有一个错误;
private static String url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=chocolate";
//names
final String QUERY = "query";
final String LIST = "search";
final String TITLE = "title";
final String SNIPPET = "snippet";
JSONObject searchJson = new JSONObject(searchJsonStr);
JSONObject queryObject = searchJson.getJSONObject(QUERY);
JSONArray searchObject = queryObject.getJSONArray(LIST);
JSONObject titObject = (JSONObject) searchObject.get(0);
String title = titObject.getString(TITLE);
String description = titObject.getString(SNIPPET);
我的错误是;
searchJsonStr无法解析为变量
答案 0 :(得分:0)
您收到此错误,因为您的代码中没有名为searchJsonStr的变量。
您需要先检索api请求的JSON内容,然后将其用作变量searchJsonStr。
您可以使用此代码:
String searchJsonStr = null;
URL url = new URL("https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=chocolate");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
searchJsonStr = getStringFromInputStream(in);
} else {
searchJsonStr = null;
}