【发布时间】:2019-10-24 15:48:26
【问题描述】:
我正在尝试解析 JSON 对象,以便可以从 Google Books API 获取图书项目列表。不幸的是,当我尝试从对象中提取 JSONArray 时,我的项目遇到了障碍。它抛出了 java.lang.StackOverflowError 异常。
该对象似乎已从服务器的响应字符串中成功解析,但是,当我尝试从该对象获取一个数组时,我不确定这里到底发生了什么。对此的任何指针表示赞赏,特别是因为我是 JSON 操作的相对新手。
static ArrayList<BookItem> getBooks(String queryString){
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String bookJSONString = null;
mListBooks = new ArrayList<>();
try {
Uri builtUri = Uri.parse(BOOK_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, queryString)
.appendQueryParameter(MAX_RESULTS, "10")
.build();
URL requestURL = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) requestURL.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
if(builder.length() == 0) return null;
bookJSONString = builder.toString();
Log.d(TAG, bookJSONString);
JSONObject jsonObject = new JSONObject(bookJSONString);
JSONArray jsonArray = jsonObject.getJSONArray("items");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return mListBooks;
}
}
错误信息:
Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate org.json.JSONArray.toString()
通常,我认为这种错误是由递归引起的,但我正在努力寻找可能发生这种情况的地方。罪魁祸首似乎是JSONArray jsonArray = jsonObject.getJSONArray("items"); 我可能解析这一切都错了,解决方案很可能是盯着我这里...
【问题讨论】:
-
你能发布json吗?
-
是的,您的 JSON 也可能有问题。请发布 JSON。
-
是的。这是:pastebin.com/BQWxUdug
-
我建议使用 gson