簡體   English   中英

在 Spring 中讀取 Content-Type 應用程序/json

[英]Reading Content-Type application/json in Spring

就像在try-to-use-spring-boot-rest-to-read-json-string-from-post 中一樣,我想從 Spring RestController 中的 POST 請求中讀取 json 有效負載。 使用內容類型“text/plain”沒有問題,但使用“application/json”反序列化失敗,我得到一個 MessageNotReadable 異常。 但實際上內容再簡單不過了,它只是一個空的json對象“{}”。 可能是缺少所需的轉換器嗎? 我使用 Spring Root 版本 1.2.3.RELEASE。

編碼示例

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json")
@ResponseBody
public Definitions createOrUpdateDefinitions(HttpEntity<String> httpEntity) throws IOException { ... }

卷曲呼叫

curl -H  "Content-type: application/json" -X POST -d '{}' http://localhost:8080/deepdefinitions

錯誤

{"timestamp":1434397457853,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Could not read JSON: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: org.apache.catalina.connector.CoyoteInputStream@122f9ce3; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token\n at [Source: org.apache.catalina.connector.CoyoteInputStream@122f9ce3; line: 1, column: 1]","path":"/deepdefinitions"}

來自Spring REST 指南

AcceptContent-Type HTTP 標頭可用於描述 HTTP 請求中發送或請求的內容。 如果客戶端請求 JSON 格式的響應,它可以將Accept設置為application/json 相反,在發送數據時,將Content-Type設置為application/xml告訴客戶端請求中發送的數據是 XML。

看來您的控制器只處理 Accept 標頭:

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json")

您需要將其更改為:

@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json, Content-type=application/json")

@RequestMapping注釋中還有可用的consumesproduces 元素

Spring MVC 文檔建議:

盡管您可以使用媒體類型通配符匹配Content-TypeAccept標頭值(例如“content-type=text/*”將匹配“text/plain”和“text/html”),但建議使用而是分別consumesproduces條件。 它們專門用於該目的。


根據您的相關帖子,您應該將方法簽名更改為:

@ResponseBody
public Definitions createOrUpdateDefinitions(@RequestBody String value, HttpEntity<String> httpEntity) throws IOException

我認為你也應該改變你的 curl 命令,如下所示。 這是因為{} (JavaScript對象字面量)會映射到一個對象,而要映射到一個字符串,您應該使用空字符串''字面量。

curl -H "Content-type: application/json" -X POST -d '' http://localhost:8080/deepdefinitions

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM