Android Studio使用Volley解析根为对象/数组的JSON提取title值异常求助
问题根因
- 字符串比较逻辑错误:Java 中对比字符串内容不能使用
==,需调用equals()方法,你现有代码中json == "array"、json == "object"的判断存在很高的失效概率。 - 字段结构解析错误:两个接口返回的
title字段并非纯字符串类型,而是嵌套的 JSONObject 结构,格式为{"value":"实际标题文本"},你直接调用getString("title")会把整个 JSONObject 转为字符串输出,就会出现带额外括号的问题。 - 根为 JSONObject 时的解析逻辑错误:第二个接口根对象下的
title是 JSONObject 类型,你原有代码错误将其当做 JSONArray 遍历,会触发解析异常。
修复后代码
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext()); String url = "https://jhookcrochet.eu/?_format=json"; StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { String jsonType = ""; try { new JSONObject(response); jsonType = "object"; } catch (JSONException ex) { jsonType = "array"; } if ("array".equals(jsonType)) { try { JSONArray jsonArray = new JSONArray(response); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jresponse = jsonArray.getJSONObject(i); // 提取title的value值 JSONObject titleObj = jresponse.getJSONObject("title"); String title = titleObj.getString("value"); // body也是同结构,按需修改 JSONObject bodyObj = jresponse.getJSONObject("body"); String body = bodyObj.getString("value"); Log.d("title", title); Log.d("body", body); textView.append("Title: " + title + "\n"); } } catch (JSONException e) { textView.append("NO\n"); e.printStackTrace(); } } else if ("object".equals(jsonType)) { textView.append("Yep, that is an object\n"); try { JSONObject jsonResponse = new JSONObject(response); // 直接取title对象再拿value JSONObject titleObj = jsonResponse.getJSONObject("title"); String title = titleObj.getString("value"); Log.d("title", title); textView.append("Title: " + title + "\n"); } catch (JSONException e) { e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("error",error.toString()); } }); rq.add(request); // Inflate the layout for this fragment return root;
内容的提问来源于stack exchange,提问作者Dennis。
相关产品推荐
相关产品推荐

