繁体   English   中英

如何从嵌套的 json volley/android 中检索数据

[英]How to retrieve data from nested json volley/android

我想从这个 JSON 中获得所有标题。 我正在使用 Volley 库。

JSON source: 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

您可以执行以下操作:

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());

Output:

[CSE522, EEE, BBA, MBA, SWE555, CSE625, CSE721, CSE250, CSE775, CSE499]

参考: https://stackoverflow.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 用于网络任务,因为它使网络任务更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM