如何从嵌套的 json volley/android 中检索数据
Posted
技术标签:
【中文标题】如何从嵌套的 json volley/android 中检索数据【英文标题】:How to retrieve data from nested json volley/android 【发布时间】:2021-07-18 07:51:36 【问题描述】:我想从这个 JSON 中获取所有标题。我正在使用 Volley 库。
JSON 源:https://sheets.googleapis.com/v4/spreadsheets/1AtYF5g2_A3AiAhejVj595bDLxO1zoGq7PNGjbdV9U8Q?fields=sheets.properties.title&key=AIzaSyDLeY5OUn8KKHeBY6PSZJbBE8rIIME_9dc
我的代码:
public void getAllName()
String urls = "https://sheets.googleapis.com/v4/spreadsheets/1AtYF5g2_A3AiAhejVj595bDLxO1zoGq7PNGjbdV9U8Q?fields=sheets.properties.title&key=AIzaSyDLeY5OUn8KKHeBY6PSZJbBE8rIIME_9dc";
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urls,
null, new Response.Listener<JSONObject>()
@Override
public void onResponse(JSONObject response)
try
JSONObject feedObj = response.getJSONObject("sheets");
JSONArray entryArray = feedObj.getJSONArray("properties");
catch (JSONException e)
e.printStackTrace();
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
);
queue.add(jsonObjectRequest);
请告诉我如何获得所有标题... TIA
【问题讨论】:
【参考方案1】:您可以执行以下操作:
JSONArray jsonArray = jsonObject.getJSONArray("sheets");
List<String> titles = IntStream.range(0,jsonArray.length())
.mapToObj(i -> jsonArray.getJSONObject(i)
.getJSONObject("properties")
.getString("title"))
.collect(Collectors.toList());
输出:
[CSE522, EEE, BBA, MBA, SWE555, CSE625, CSE721, CSE250, CSE775, CSE499]
【讨论】:
完美运行。非常感谢。 @BuildSlayer 我很高兴能帮上忙 :) 你可以尝试解决这个“***.com/questions/67244846/…”@BuildSlayer【参考方案2】:参考:https://***.com/a/49839058/13533028
从您的 Json 响应中,您的标题数据位于工作表内的属性中。 可以使用 getJsonObject("name of the property") 从 Json 中检索 JsonObject
JSONObject jsonObject = new JSONObject(response);
JSONObject dataArray = jsonObject.getJSONArray("sheets");
JSONArray properties= dataArray.getJsonObject(YOUR_ELEMENT_NO);
现在你可以以同样的方式使用properties.title,随心所欲地使用它。
另外,我建议将 Retrofit 用于网络任务,因为它使网络任务更容易。
【讨论】:
以上是关于如何从嵌套的 json volley/android 中检索数据的主要内容,如果未能解决你的问题,请参考以下文章
在 Hive 中,这种模式如何从 json 数组中识别嵌套的 json?
如何从通过 Moya.Response 查询返回的对象解析嵌套的 JSON 数组