【问题标题】:Spring mvc and Jackson MismatchedInputException on json contentjson内容上的Spring mvc和Jackson MismatchedInputException
【发布时间】: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


【解决方案1】:

对我有用的解决方案是删除:

@RequestBody final String body

改为使用:

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

还将生产参数添加到:

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

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2019-06-24
    • 1970-01-01
    • 2021-01-25
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2012-02-28
    相关资源
    最近更新 更多