JsonParseException: Unrecognized token 'XX': was expecting ('true', 'false' or 'null')

安卓用Volley做為請(qǐng)求框架,后臺(tái)用SpringMvc,數(shù)據(jù)傳輸格式用Json。
請(qǐng)求的時(shí)候報(bào)一個(gè)錯(cuò)。

{
    "timestamp": 1498636645291,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "Could not read document: Unrecognized token 'diffTime': was expecting ('true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@3a2ef3ba; line: 1, column: 10]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'diffTime': was expecting ('true', 'false' or 'null')\n at [Source: java.io.PushbackInputStream@3a2ef3ba; line: 1, column: 10]",
    "path": "/data/country/update"
}

掙扎許久后,發(fā)現(xiàn)是客戶端Volley框架發(fā)出請(qǐng)求時(shí)的數(shù)據(jù)格式不對(duì)。

修改如下即可
在Volley框架中的Request.java類:

    private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
//        StringBuilder encodedParams = new StringBuilder();
//        try {
//            for (Map.Entry<String, String> entry : params.entrySet()) {
//                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
//                encodedParams.append('=');
//                encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
//                encodedParams.append('&');
//            }
//            return encodedParams.toString().getBytes(paramsEncoding);
//        } catch (UnsupportedEncodingException uee) {
//            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
//        }
        try{
            JSONObject jsonObject = new JSONObject(params);
            return jsonObject.toString().getBytes(paramsEncoding);
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

自己封裝的繼承Request<T>類,也需要補(bǔ)充點(diǎn)代碼:
主要是getHeaders()、getBodyContentType()、parseNetworkResponse()方法

public class StringRequestJsonResult extends Request<JSONObject> {

    protected static final String PROTOCOL_CHARSET = "utf-8";

    private final Response.Listener<JSONObject> mListener;

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        params.put("Accept", "application/json");
        params.put("Content-Type", "application/json; charset=UTF-8");
        return params;
    }

    @Override
    public String getBodyContentType() {
        return "application/json; charset=" + getParamsEncoding();
    }

    /**
     * Creates a new request with the given method.
     *
     * @param method the request {@link Method} to use
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequestJsonResult(int method, String url, Response.Listener<JSONObject> listener,
                                   Response.ErrorListener errorListener) {
        super(method, url, errorListener);


        mListener = listener;
    }

    /**
     * Creates a new GET request.
     *
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequestJsonResult(String url, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        this(Method.GET, url, listener, errorListener);
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            return Response.success(JSON.parseObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}

以上,完畢。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評(píng)論 25 708
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,697評(píng)論 19 139
  • 1. 功能介紹 1.1. Volley Volley 是 Google 推出的 Android 異步網(wǎng)絡(luò)請(qǐng)求框架和...
    愛碼士平頭哥閱讀 1,928評(píng)論 0 9
  • 忘了有多久沒有社交了,整天宅在家里,慢慢的,朋友間也不聯(lián)系了,更不出去玩,之前帶孩子還情有可原,現(xiàn)在孩子回老家了,...
    簫藍(lán)錄閱讀 254評(píng)論 0 0
  • 繽智是廣汽本田旗下首款SUV,在推出2017款之后除了2月份做到了月月銷量破萬(wàn)。今天我們就來(lái)聊一聊這款2017新款...
    SUV頭條閱讀 249評(píng)論 0 0

友情鏈接更多精彩內(nèi)容