如何从API返回的JSON数组中获取无键名的JSON对象?Volley代码适配咨询
解决Volley获取无键名JSON对象的问题
嘿,我来帮你搞定这个Volley解析JSON的问题~首先得明确一点:JSON语法里不存在真正无键名的对象属性,你说的类似{0}, {1}的情况,大概率是下面两种场景之一,我分别给你对应的解决方案:
场景1:数组元素本身就是目标对象
如果你的API返回的result数组里,每个元素直接就是包含title、subtitle等字段的对象(结构大概像下面这样):
{ "result": [ { "title": "书名1", "subtitle": "副标题1", "authors": ["作者A"], "publisher": "出版社A" }, { "title": "书名2", "subtitle": "副标题2", "authors": ["作者B"], "publisher": "出版社B" } ] }
那你完全不需要JSONObject volumeObj = itemsObj.getJSONObject("");这一行,直接把itemsObj当作目标对象来用就行,修改后的代码如下:
RequestQueue queue = Volley.newRequestQueue(MainActivity.this); JsonObjectRequest booksObjrequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { progressBar.setVisibility(View.GONE); try { JSONArray itemsArray = response.getJSONArray("result"); for (int i = 0; i < itemsArray.length(); i++) { // 直接用itemsObj作为目标对象,跳过多余的getJSONObject步骤 JSONObject volumeObj = itemsArray.getJSONObject(i); String title = volumeObj.optString("title"); String subtitle = volumeObj.optString("subtitle"); JSONArray authorsArray = volumeObj.getJSONArray("authors"); String publisher = volumeObj.optString("publisher"); String publishedDate = volumeObj.optString("publishedDate"); String description = volumeObj.optString("description"); // 后续处理逻辑... } } catch (JSONException e) { e.printStackTrace(); // 别忘了处理异常哦 } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 错误处理逻辑 progressBar.setVisibility(View.GONE); } }); queue.add(booksObjrequest);
场景2:数组元素是包含数字键的对象
如果你的API返回的result数组里,每个元素是一个只有数字键的对象(结构大概像下面这样):
{ "result": [ { "0": { "title": "书名1", "subtitle": "副标题1", "authors": ["作者A"] } }, { "1": { "title": "书名2", "subtitle": "副标题2", "authors": ["作者B"] } } ] }
这时候你可以通过两种方式获取目标对象:
方案A:遍历键获取(更通用,不管键是什么数字都能适配)
// 循环内修改这部分代码 JSONObject itemsObj = itemsArray.getJSONObject(i); // 获取对象的所有键,取第一个键对应的对象 Iterator<String> keys = itemsObj.keys(); if (keys.hasNext()) { String targetKey = keys.next(); JSONObject volumeObj = itemsObj.getJSONObject(targetKey); // 后续的title、subtitle等解析逻辑不变 String title = volumeObj.optString("title"); // ... }
方案B:用循环索引作为键(如果键刚好是循环的i值)
// 循环内修改这部分代码 JSONObject itemsObj = itemsArray.getJSONObject(i); // 直接用当前循环的索引转为字符串作为键 JSONObject volumeObj = itemsObj.getJSONObject(String.valueOf(i)); // 后续解析逻辑不变
内容的提问来源于stack exchange,提问作者Tony Shin
相关产品推荐
相关产品推荐

