making a GSON request using volley

后端 未结 3 460
既然无缘
既然无缘 2020-12-12 21:37

I have the following json response

{
  \"tag\": [
    {
      \"listing_count\": 5,
      \"listings\": [
        {
          \"source\": \"source1\",
               


        
3条回答
  •  时光取名叫无心
    2020-12-12 22:01

    Here some useful code snippets.

    GsonRequest for GET petitions:

    import com.android.volley.NetworkResponse;
    import com.android.volley.ParseError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.toolbox.HttpHeaderParser;
    import com.google.gson.Gson;
    import com.google.gson.JsonSyntaxException;
    
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Type;
    
    /**
     * Convert a JsonElement into a list of objects or an object with Google Gson.
     *
     * The JsonElement is the response object for a {@link com.android.volley.Request.Method} GET call.
     *
     * @author https://plus.google.com/+PabloCostaTirado/about
     */
    public class GsonGetRequest extends Request
    {
        private final Gson gson;
        private final Type type;
        private final Response.Listener listener;
    
        /**
         * Make a GET request and return a parsed object from JSON.
         *
         * @param url URL of the request to make
         * @param type is the type of the object to be returned
         * @param listener is the listener for the right answer
         * @param errorListener  is the listener for the wrong answer
         */
        public GsonGetRequest
        (String url, Type type, Gson gson,
         Response.Listener listener, Response.ErrorListener errorListener)
        {
            super(Method.GET, url, errorListener);
    
            this.gson = gson;
            this.type = type;
            this.listener = listener;
        }
    
        @Override
        protected void deliverResponse(T response)
        {
            listener.onResponse(response);
        }
    
        @Override
        protected Response parseNetworkResponse(NetworkResponse response)
        {
            try
            {
                String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    
                return (Response) Response.success
                        (
                                gson.fromJson(json, type),
                                HttpHeaderParser.parseCacheHeaders(response)
                        );
            }
            catch (UnsupportedEncodingException e)
            {
                return Response.error(new ParseError(e));
            }
            catch (JsonSyntaxException e)
            {
                return Response.error(new ParseError(e));
            }
        }
    }
    

    GsonRequest for POST petitions:

        import com.android.volley.NetworkResponse;
        import com.android.volley.ParseError;
        import com.android.volley.Response;
        import com.android.volley.toolbox.HttpHeaderParser;
        import com.android.volley.toolbox.JsonRequest;
        import com.google.gson.Gson;
        import com.google.gson.JsonSyntaxException;
    
        import java.io.UnsupportedEncodingException;
        import java.lang.reflect.Type;
    
        /**
         * Convert a JsonElement into a list of objects or an object with Google Gson.
         *
         * The JsonElement is the response object for a {@link com.android.volley.Request.Method} POST call.
         *
         * @author https://plus.google.com/+PabloCostaTirado/about
         */
        public class GsonPostRequest extends JsonRequest
        {
            private final Gson gson;
            private final Type type;
            private final Response.Listener listener;
    
            /**
             * Make a GET request and return a parsed object from JSON.
             *
             * @param url URL of the request to make
             * @param type is the type of the object to be returned
             * @param listener is the listener for the right answer
             * @param errorListener  is the listener for the wrong answer
             */
            public GsonPostRequest
            (String url, String body, Type type, Gson gson,
             Response.Listener listener, Response.ErrorListener errorListener)
            {
                super(Method.POST, url, body, listener, errorListener);
    
                this.gson = gson;
                this.type = type;
                this.listener = listener;
            }
    
            @Override
            protected void deliverResponse(T response)
            {
                listener.onResponse(response);
            }
    
            @Override
            protected Response parseNetworkResponse(NetworkResponse response)
            {
                try
                {
                    String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    
                    return (Response) Response.success
                            (
                                    gson.fromJson(json, type),
                                    HttpHeaderParser.parseCacheHeaders(response)
                            );
                }
                catch (UnsupportedEncodingException e)
                {
                    return Response.error(new ParseError(e));
                }
                catch (JsonSyntaxException e)
                {
                    return Response.error(new ParseError(e));
                }
            }
        }
    

    This is how you use it for JSON objects:

        /**
             * Returns a dummy object
             *
             * @param listener is the listener for the correct answer
             * @param errorListener is the listener for the error response
             *
             * @return @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonGetRequest}
             */
            public static GsonGetRequest getDummyObject
            (
                    Response.Listener listener,
                    Response.ErrorListener errorListener
            )
            {
                final String url = "http://www.mocky.io/v2/55973508b0e9e4a71a02f05f";
    
                final Gson gson = new GsonBuilder()
                        .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
                        .create();
    
                return new GsonGetRequest<>
                        (
                                url,
                                new TypeToken() {}.getType(),
                                gson,
                                listener,
                                errorListener
                        );
            }
    

    This is how you use it for JSON arrays:

    /**
         * Returns a dummy object's array
         *
         * @param listener is the listener for the correct answer
         * @param errorListener is the listener for the error response
         *
         * @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonGetRequest}
         */
        public static GsonGetRequest> getDummyObjectArray
        (
                Response.Listener> listener,
                Response.ErrorListener errorListener
        )
        {
            final String url = "http://www.mocky.io/v2/5597d86a6344715505576725";
    
            final Gson gson = new GsonBuilder()
                    .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
                    .create();
    
            return new GsonGetRequest<>
                    (
                            url,
                            new TypeToken>() {}.getType(),
                            gson,
                            listener,
                            errorListener
                    );
        }
    

    This is how you use it for POST calls:

    /**
         * An example call (not used in this example app) to demonstrate how to do a Volley POST call
         * and parse the response with Gson.
         *
         * @param listener is the listener for the success response
         * @param errorListener is the listener for the error response
         *
         * @return {@link com.sottocorp.sotti.okhttpvolleygsonsample.api.GsonPostRequest}
         */
        public static GsonPostRequest getDummyObjectArrayWithPost
                (
                        Response.Listener listener,
                        Response.ErrorListener errorListener
                )
        {
            final String url = "http://PostApiEndpoint";
            final Gson gson = new GsonBuilder()
                    .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
                    .create();
    
            final JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", "Ficus");
            jsonObject.addProperty("surname", "Kirkpatrick");
    
            final JsonArray squareGuys = new JsonArray();
            final JsonObject dev1 = new JsonObject();
            final JsonObject dev2 = new JsonObject();
            dev1.addProperty("name", "Jake Wharton");
            dev2.addProperty("name", "Jesse Wilson");
            squareGuys.add(dev1);
            squareGuys.add(dev2);
    
            jsonObject.add("squareGuys", squareGuys);
    
            return new GsonPostRequest<>
                    (
                            url,
                            jsonObject.toString(),
                            new TypeToken()
                            {
                            }.getType(),
                            gson,
                            listener,
                            errorListener
                    );
        }
    }
    

    All the code is taken from here, and you have a blog post about how to use OkHttp, Volley and Gson here.

提交回复
热议问题