[英]How to retrieve data from nested json volley/android
I want to get all titles from this JSON.我想从这个 JSON 中获得所有标题。 I am using the Volley library.
我正在使用 Volley 库。
JSON source: https://sheets.googleapis.com/v4/spreadsheets/1AtYF5g2_A3AiAhejVj595bDLxO1zoGq7PNGjbdV9U8Q?fields=sheets.properties.title&key=AIzaSyDLeY5OUn8KKHeBY6PSZJbBE8rIIME_9dc JSON source: https://sheets.googleapis.com/v4/spreadsheets/1AtYF5g2_A3AiAhejVj595bDLxO1zoGq7PNGjbdV9U8Q?fields=sheets.properties.title&key=AIzaSyDLeY5OUn8KKHeBY6PSZJbBE8rIIME_9dc
My Code:我的代码:
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);
}
Please tell me how to get all the titles... TIA请告诉我如何获得所有头衔... TIA
You can do the following:您可以执行以下操作:
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: Output:
[CSE522, EEE, BBA, MBA, SWE555, CSE625, CSE721, CSE250, CSE775, CSE499]
Ref: https://stackoverflow.com/a/49839058/13533028参考: https://stackoverflow.com/a/49839058/13533028
From your Json Response, your title data is inside properties which are inside sheets.从您的 Json 响应中,您的标题数据位于工作表内的属性内。 JsonObject can be retrieved from Json using getJsonObject("name of the property")
可以使用 getJsonObject("name of the property") 从 Json 检索 JsonObject
JSONObject jsonObject = new JSONObject(response);
JSONObject dataArray = jsonObject.getJSONArray("sheets");
JSONArray properties= dataArray.getJsonObject(YOUR_ELEMENT_NO);
now you can use properties.title in the same way and use it as you like.现在您可以以相同的方式使用 properties.title 并随心所欲地使用它。
Also, I would suggest using Retrofit for networking tasks since it makes networking tasks much easier.另外,我建议将 Retrofit 用于网络任务,因为它使网络任务更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.