1. 程式人生 > 實用技巧 >JSON parse error: Unrecognized token 'xxx': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false');

JSON parse error: Unrecognized token 'xxx': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false');

問題現象

  Spring Boot專案中,訪問後臺介面時,報錯:

    [ ERROR] [2021-01-20 11:15:15.214] com.xxx.test.handle.ExceptionHandle [44] [http-nio-127.0.0.1-8855-exec-6] [handleException] - JSON parse error: Unrecognized token 'xxx': was expecting       (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException:

      Unrecognized token 'xxx': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
      at [Source: (PushbackInputStream); line: 1, column: 19]

原因分析

  很明顯,這是訪問介面的引數格式不對造成的,具體而言,和介面的@RequestBody關鍵字有關,在後臺引數反序列化過程中出錯了。

  介面如下:

    

1     @PostMapping("")
2     public
ResponseEntity<ResultEntity<Long>> test(@RequestBody TestData TestData){ 3 Long startTime = System.currentTimeMillis(); 4 }

  

解決方法

  方法1:前臺是通過ajax提交時,

    使用JSON.stringify(data)序列化請求引數

  方法2:如果是通過HttpClient模擬請求

    在給HTTPPOST例項新增請求引數時,就不能使用UrlEncodedFormEntity的方式新增,這次遇到的坑就是使用了這個

 1         // 封裝post請求引數
 2         if (null != paramMap && paramMap.size() > 0) {
 3             List<NameValuePair> nvps = new ArrayList<NameValuePair>();            
 4             // 通過map整合entrySet方法獲取entity
 5             Set<Entry<String, Object>> entrySet = paramMap.entrySet();
 6             // 迴圈遍歷,獲取迭代器
 7             for (Entry<String, Object> mapEntry : entrySet) {
 8                  nvps.add(new BasicNameValuePair(mapEntry.getKey(), JSON.toJSONString(mapEntry.getValue())));
 9             }
10 11 // 為httpPost設定封裝好的請求引數 12 try { 13 httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); 14 } catch (UnsupportedEncodingException e) { 15 e.printStackTrace(); 16 }

    修改為UrlEncodedFormEntity的父類StringEntity 即可,修改後的程式碼如下:

    

 1  // 封裝post請求引數
 2         if (null != paramMap && paramMap.size() > 0) {
 3             JSONObject jsonObject = new JSONObject();           
 4             // 通過map整合entrySet方法獲取entity
 5             Set<Entry<String, Object>> entrySet = paramMap.entrySet();
 6             // 迴圈遍歷,獲取迭代器
 7             for (Entry<String, Object> mapEntry : entrySet) {
 8                 jsonObject.put(mapEntry.getKey(), mapEntry.getValue());
 9             }
10             
11             // 為httpPost設定封裝好的請求引數
12             try {
13                 httpPost.setEntity(new StringEntity(jsonObject.toString()));
14             } catch (UnsupportedEncodingException e) {
15                 e.printStackTrace();
16             }
View Code

    修改後,重新啟動即可正常訪問。