Spring json 内容上的 mvc 和 Jackson MismatchedInputException

Spring mvc and Jackson MismatchedInputException on json content

我正在将 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 final String body

改为使用:

final HttpServletRequest request
...
InputStream stream = request.getInputStream();
byte[] result = ByteStreams.toByteArray(stream);
String body =new String(result,"UTF-8");

还将 produces 参数添加到:

@RequestMapping(method = RequestMethod.POST, produces = "text/plain; charset=ISO-8859-1")