就像在trying-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"}
答案 0 :(得分:0)
Accept
和Content-Type
HTTP标头可用于描述HTTP请求中发送或请求的内容。如果客户端以JSON请求响应,则可以将Accept
设置为application/json
。相反,在发送数据时,将Content-Type
设置为application/xml
会告诉客户端请求中发送的数据是XML。
您的Controller似乎只处理Accept标头:
@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json")
您需要将其更改为:
@RequestMapping(value = "/deepdefinitions", method = POST, headers = "Accept=application/json,Content-type=application/json")
还有Consumes and Produces个注释。
虽然您可以使用媒体类型通配符匹配
Content-Type
和Accept
标头值(例如&#34; content-type = text / *&#34;将匹配&#34 ; text / plain&#34;和&#34; text / html&#34;),建议分别使用consumes
和produces
条件。它们专门用于此目的。
通过相关帖子,您应该将方法签名更改为:
public @ResponseBody Definitions createOrUpdateDefinitions(@RequestBody String value, HttpEntity httpEntity) throws IOException
我认为你也应该改变你的curl命令,如下所示。这是因为{}
(Javascript Object literal)会映射到一个对象并映射到一个String,你应该使用一个空字符串''
文字。
curl -H "Content-type: application/json" -X POST -d '' http://localhost:8080/deepdefinitions