Reputation: 139
I want to get all titles from this JSON. I am using the Volley library.
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
Upvotes: 0
Views: 140
Reputation: 5183
Ref:https://stackoverflow.com/a/49839058/13533028
From your Json Response, your title data is inside properties which are inside sheets. JsonObject can be retrieved from Json using getJsonObject("name of the property")
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.
Also, I would suggest using Retrofit for networking tasks since it makes networking tasks much easier.
Upvotes: 0
Reputation: 2776
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:
[CSE522, EEE, BBA, MBA, SWE555, CSE625, CSE721, CSE250, CSE775, CSE499]
Upvotes: 1