问题
I am trying to call a rest end point using Volley (HTTP library) in Android/Java app. Here is my code,
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://covid19datasl.herokuapp.com/countries";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error");
}
});
But it gives me an String a response like this,
[{"country":"USA","countryCode":"US"},{"country":"India","countryCode":"IN"},{"country":"Brazil","countryCode":"BR"}]
How do I convert this String
to an itaratable object?
回答1:
No need for any other libraries beside Volley.
Use Volleys JsonArrayRequest for retrieving JSONArray
responses.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://my-json-feed";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// do something with the response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
// Add request to queue
queue.add(jsonArrayRequest);
来源:https://stackoverflow.com/questions/65000363/how-convert-a-string-response-to-an-iterable-object