making a GSON request using volley

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

I have the following json response

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


        
3条回答
  •  -上瘾入骨i
    2020-12-12 21:58

    I just made a custom json request which is based on Jackson library instead of Gson.

    One thing I want to point out (it took my many hours to figure out...): if you want to support POST Json parameter as well, you should extend from JsonRequest instead of Request. Otherwise your Json request body will be url-encoded, on the server side you cannot convert it back to java object.

    Here is my json request class, which is based on Jackson and supports Json parameter and header:

        public class JacksonRequest extends JsonRequest {
    
        private final ObjectMapper objectMapper = new ObjectMapper();
        private final Class responseClass;
        private final Map headers;
    
        private String requestBody = null;
        private static final String PROTOCOL_CHARSET = "utf-8";
    
        /**
         * POST method without header
         */
        public JacksonRequest(String url,
                              Object parameterObject,
                              Class responseClass,
                              Response.Listener listener,
                              Response.ErrorListener errorListener) {
    
            this(Method.POST, url, null, parameterObject, responseClass, listener, errorListener);
        }
    
        /**
         * @param method see also com.android.volley.Request.Method
         */
        public JacksonRequest(int method,
                              String url,
                              Map headers,
                              Object parameterObject,
                              Class responseClass,
                              Response.Listener listener,
                              Response.ErrorListener errorListener) {
    
            super(method, url, null, listener, errorListener);
    
            if (parameterObject != null)
                try {
                    this.requestBody = objectMapper.writeValueAsString(parameterObject);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
    
            this.headers = headers;
            this.responseClass = responseClass;
        }
    
        @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));
                ResponseType result = objectMapper.readValue(json, responseClass);
                return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
    
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JsonMappingException e) {
                return Response.error(new ParseError(e));
            } catch (JsonParseException e) {
                return Response.error(new ParseError(e));
            } catch (IOException e) {
                return Response.error(new ParseError(e));
            }
        }
    
        /**
         * Cannot call objectMapper.writeValueAsString() before super constructor, so override the same getBody() here.
         */
        @Override
        public byte[] getBody() {
            try {
                return requestBody == null ? null : requestBody.getBytes(PROTOCOL_CHARSET);
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                        requestBody, PROTOCOL_CHARSET);
                return null;
            }
        }
    
    }
    

提交回复
热议问题