Parse Android Volley JSONArray response
Asked Answered
M

3

10

I'm sending a JSONArray GET request with Volley, and it's returning the specified JSON array. Here's my Request:

JsonArrayRequest getRequest = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>()
                    {
                        @Override public void onResponse(JSONArray response) {

                            Log.d("Response", response.toString());
                        }
                    },
                    new Response.ErrorListener()
                    {
                        @Override public void onErrorResponse(VolleyError error) {
                            Log.d("Error.Response", error.toString());
                        }
                    }
                  );
                  VolleySingleton.getInstance(this).addToRequestQueue(getRequest); //Call to get dashboard feed
}

As you can see, I'm currently just logging out the response. I want to parse the Array though and display the results in a list view. The documentation for this isn't great, and I'm pretty green in terms of Android dev. What is the proper way to parse a JSON array from Volley and display the results in a list view? I've gathered that I should use parseNetworkResponse, but not sure how to implement.

Marcelline answered 25/6, 2014 at 5:50 Comment(0)
M
41

I'd recommend to stick to the GSON library for JSON parsing. Here's how a Volley request with embedded JSON processing could look then:

import java.io.UnsupportedEncodingException;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * Volley GET request which parses JSON server response into Java object.
 */
public class GsonRequest<T> extends Request<T> {

    /** JSON parsing engine */
    protected final Gson gson;

    /** class of type of response */
    protected final Class<T> clazz;

    /** result listener */
    private final Listener<T> listener;

    public GsonRequest(String url, Class<T> clazz, Listener<T> listener, 
            ErrorListener errorListener) {
        super(Method.GET, url, errorListener);

        this.clazz = clazz;
        this.listener = listener;
        this.gson = new Gson();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

Let's imagine you have a server method located at http://example.com/api/persons/ which returns a JSON array of Person; Person is as follows:

public class Person {
    String firstName;
    String lastName;
}

We can call the abovementioned method like this:

GsonRequest<Person[]> getPersons = 
        new GsonRequest<Person[]>("http://example.com/api/persons/", Person[].class,

            new Listener<Person[]>() {
                @Override
                public void onResponse(Person[] response) {
                    List<Person> persons = Arrays.asList(response);
                    // TODO deal with persons
                }

            }, new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO deal with error
                }
            });

VolleyQueue.get().add(getPersons);

And finally in response listener we get an array of Person which can be converted to list and fed to ListView's adapter.

Matti answered 26/6, 2014 at 15:0 Comment(4)
Where does the last code snippet go? And where is VolleyQueue defined?Alcyone
can we use the type token method here?Businesslike
Nice sample.its helped.!Sacral
@Alcyone try like this VolleyHelper.getInstance(getActivity()).addToRequestQueue(getPersons); Create a volley helper class to add the request queue. if you need the sample i can provide !.Sacral
C
0

you can use Gson project to working with json in java and android app ,it is so simple this link is a sample link of using gson

How To Convert Java Object To / From JSON (Gson)

Canty answered 25/6, 2014 at 6:1 Comment(0)
W
0

You can either use the native JSONParsor in the android framework your requirements are comparatively less and the JSON is simple. Here is a link for the tutorial.

But if you are using complex JSON objects, use libraries like

  • GSON
  • Jackson

I find GSON easier and more effective to use. You know more about it from Here

Wysocki answered 25/6, 2014 at 6:4 Comment(2)
Thank you, I will likely use GSON. Can you elaborate on how to actually parse an Array though? The example you referenced uses AsyncTask, not Volley so it's a bit confusing. I've found there are lots of resources on parsing a JSONObject, but not as many for an Array which is what I'm dealing with.Marcelline
pass the response string from volley to gsonWysocki

© 2022 - 2024 — McMap. All rights reserved.