how to parse android volley gson request to a list / collection of objects

前端 未结 2 1856
醉话见心
醉话见心 2021-01-06 09:18

I am trying to make a Gson request using android volley. Currently it it working correctly and I am very happy. However why I try and get a List<> or a collection of obje

2条回答
  •  鱼传尺愫
    2021-01-06 09:43

    I recently needed to implement a solution myself so here you go. Custom GsonArrayRequest.

    public class GsonArrayRequest extends Request> {
         private final Gson gson = new Gson();
         private final Class clazz;
         private final Map headers;
         private final Response.Listener> listener;
    
        /**
         * Make a GET request and return a parsed object from JSON.
         * @param clazz Relevant class object, for Gson's reflection
         * @param url     URL of the request to make
         * @param headers Map of request headers
         */
         public GsonArrayRequest(String url, Class clazz, Map headers,
                            Response.Listener> listener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }
    
    @Override
    public Map getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }
    
    @Override
    protected Response> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
    
            Type listType = com.google.gson.internal.$Gson$Types.newParameterizedTypeWithOwner(null, ArrayList.class, clazz);
            ArrayList tList = gson.fromJson(json, listType);
            return Response.success(
                    tList,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
    
         @Override
         protected void deliverResponse(ArrayList response) {
             listener.onResponse(response);
         }
     }
    

    You can use it like this:

    GsonArrayRequest gsonArrayRequest = new GsonArrayRequest<>(
            url, AngryPugs.class, null, new Response.Listener>() {
        @Override
        public void onResponse(ArrayList response) {
            // your list here
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
    
        }
    });
    

    After adding the request

     VolleySingleton.getInstance(this).addToRequestQueue(gsonArrayRequest);
    

提交回复
热议问题