Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making a GSON request using volley

I have the following json response

{
  "tag": [
    {
      "listing_count": 5,
      "listings": [
        {
          "source": "source1",
          "data": {
            "image": "image1",
            "name": "name1"
          },
          "name": "name1"
        }
      ]
    },
    {
      "listing_count": 5,
      "listings": [
        {
          "source": "source2",
          "data": {
            "image": "imag2",
            "name": "name2"
          },
          "name": "name2"
        }
      ]
    }
  ]
}

I have created the following classes for GSON request. How do I make the GSON request and store the values for the response using a volley request. What should the GSON request be like?

public class TagList {

ArrayList<Tag> tags;

public static class Tag {
    int listing_count;
    ArrayList<Listings> listings;

    public int getListing_count() {
        return listing_count;
    }

    public void setListing_count(int listing_count) {
        this.listing_count = listing_count;
    }

    public ArrayList<Listings> getListings() {
        return listings;
    }

    public void setListings(ArrayList<Listings> listings) {
        this.listings = listings;
    }

}

public static class Listings {
    String source;
    Data data;
    String name;

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

public static class Data {
    String image;
    String name;

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
like image 222
Abhay Sood Avatar asked Jul 02 '14 17:07

Abhay Sood


People also ask

How do I make a volley request?

Use newRequestQueue RequestQueue queue = Volley. newRequestQueue(this); String url = "https://www.google.com"; // Request a string response from the provided URL. StringRequest stringRequest = new StringRequest(Request. Method.

What is JSON object request?

JsonObjectRequest : A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.

How does GSON from JSON work?

Gson can work with arbitrary Java objects including objects for which you do not have the source. For this purpose, Gson provides several built in serializers and deserializers. A serializer allows to convert a Json string to corresponding Java type. A deserializers allows to convert from Java to a JSON representation.


1 Answers

Just create a GsonRequest Class as follows (taken from Android Developer Docs)

public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener;

/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url URL of the request to make
 * @param clazz Relevant class object, for Gson's reflection
 * @param headers Map of request headers
 */
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
        Listener<T> listener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.clazz = clazz;
    this.headers = headers;
    this.listener = listener;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers != null ? headers : super.getHeaders();
}

@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));
    }
}
} 

Now in your class file (Activity) just call the this class as follows:

RequestQueue queue = MyVolley.getRequestQueue();
GsonRequest<MyClass> myReq = new GsonRequest<MyClass>(Method.GET,
                                                    "http://JSONURL/",
                                                    TagList.class,
                                                    createMyReqSuccessListener(),
                                                    createMyReqErrorListener());

            queue.add(myReq);

We also need to create two methods -

  1. createMyReqSuccessListener() - receive the response from GsonRequest
  2. createMyReqErrorListener() - to handle any error

as follows:

private Response.Listener<MyClass> createMyReqSuccessListener() {
    return new Response.Listener<MyClass>() {
        @Override
        public void onResponse(MyClass response) {
           // Do whatever you want to do with response;
           // Like response.tags.getListing_count(); etc. etc.
        }
    };
}

and

private Response.ErrorListener createMyReqErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Do whatever you want to do with error.getMessage();
        }
    };
}

I hope it will make some sense.

like image 159
MSN Avatar answered Sep 20 '22 18:09

MSN