【发布时间】:2015-08-30 21:26:11
【问题描述】:
就像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"}
【问题讨论】:
-
您应该在 '@RequestMapping' 中使用 headers = "Accept=application/json" 并将 '@RequestBody' 中的序列化对象传递给您的控制器方法
-
请显示确切的异常/堆栈跟踪。
-
@Darshan,RequestMapping 中的“标题”不会改变行为。我用一个编码示例更新了这个问题。
标签: java json spring spring-mvc spring-boot