Spring mvc and Jackson MismatchedInputException on json content

Viewed 121

Im upgrading spring mvc from 4.2 to Spring mvc 5.2.0 and using Jackson 10.2.1 the following way:

controllers.xml:

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

api method:

    @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 {

        ...
    }

my curl request:

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"}'

I get an Exception of MismatchedInputException. the exception:


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]]

why is that? I send a very simple JSON.

ok, edit: when using

@RequestBody final JsonObject body

the body is {} - empty because Jackson does not know the JsonObject object.

So how can I pass body as String with --header 'Content-Type: application/json' ?

1 Answers

the solution that worked for me was to remove the:

@RequestBody final String body

and instead use:

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

also added the produces param to:

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