我正在制作一个简单的应用程序,用于扫描图书的条形码并从Google API中获取其标题和作者,
现在,这是json的网址(对于我正在扫描的特定图书)
https://www.googleapis.com/books/v1/volumes?q=isbn:9788120305960
使用此代码在字符串中获取json
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
response+=line;
}
bufferedReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("Info",response);
return response;
我将结果存储在一个字符串中,并使用此代码进行解析
(json_response
是一个字符串)
JSONObject rootObject = new JSONObject(json_response);
JSONArray items = rootObject.getJSONArray("items");
JSONObject items_object = items.getJSONObject(0);
JSONObject volume_info = items_object.getJSONObject("volumeInfo");
book.setTitle(volume_info.getString("title"));
JSONArray authors = volume_info.getJSONArray("authors");
Log.d("Info","authors array length: "+authors.length());
String author="";
for (int i =0;i<authors.length();i++)
{
author+=authors.getString(i)+", ";
}
book.setAuthor(author);
例外是:
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
我也使用logcat来查看json_response
中包含的内容,它看起来像这样
null{ "kind": "books#volumes", "totalItems": 1, "items":...
这里的null
可能会导致问题,所以...任何见解如何处理这个???
答案 0 :(得分:1)
有
null{ "kind": "books#volumes", "totalItems": 1, "items":...
表示尚未初始化response
值。
因此,您应该将其初始化为空字符串。