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

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

 

 

  

  

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM