【发布时间】:2021-02-18 02:21:56
【问题描述】:
我将 spring mvc 从 4.2 升级到 Spring mvc 5.2.0 和 通过以下方式使用 Jackson 10.2.1:
controllers.xml:
<mvc:annotation-driven>
<mvc:message-converters>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
api方法:
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public String someApi(@NotEmpty(message = "a") @RequestParam("a") final String a,
@NotEmpty @RequestHeader("b") final String b,
@NotEmpty @RequestParam("c") final String c,
@RequestHeader(value = "d", required = false, defaultValue = "None") final String d,
@RequestBody final String body) throws Exception {
...
}
我的卷曲请求:
curl --location --request POST 'http://.../the/api/?a=aaa&c=ccc' --header 'b: bbb' --header 'Content-Type: application/json' --data-raw '{"sheker":"sheker1", "kazav": "kazav1", "bla":"bla1", "blabla":"blabla1"}'
我收到 MismatchedInputException 异常。 例外:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token\n at [Source: (PushbackInputStream); line: 1, column: 1]]
这是为什么呢?我发送了一个非常简单的 JSON。
好的,编辑: 使用时
@RequestBody final JsonObject body
主体为 {} - 为空,因为 Jackson 不知道 JsonObject 对象。
那么如何使用 --header 'Content-Type: application/json' 将正文作为字符串传递?
【问题讨论】:
-
去掉@RequestBody的使用。
标签: json spring spring-mvc jackson