Skip to content
javahacks.dev
Spring MVC

Fix HttpMessageNotReadableException JSON Parse Error

Fix the 400 Bad Request caused by a request body Spring MVC cannot read, from an empty body to a wrong type, a bad enum or malformed JSON.

6 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JSON, Spring, Spring Boot, Gradle and OpenJDK logos.

A client posts JSON, and the response is a bare 400 with this in the server log:

Text
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `int` from String "abc": not a valid `int` value

Spring MVC reads the body through a message converter, and the converter threw while building the object. The client sees 400 because the request is unreadable, not because the server failed. The exact wording depends on whether your Jackson version is 2 or 3: Spring Boot 4 defaults to Jackson 3, while the structure of the message stays the same. The request path is described in how Spring MVC handles a request, and the design of the error response in building REST APIs with Spring MVC.

Read the nested message

Message fragmentCause
Required request body is missingThe body was empty or not sent
Unexpected character ('}' ...): was expecting double-quoteMalformed JSON
Cannot deserialize value of type ... from StringWrong type for a field
Cannot deserialize value of type ... from String "X": not one of the values accepted for Enum classUnknown enum constant
Cannot construct instance of ...No usable constructor; see the Jackson fix
Unrecognized fieldUnknown property; see the Jackson fix

Cause 1: the body is missing

Shell
curl -i -X POST localhost:8080/api/orders -H 'Content-Type: application/json'

No -d means no body, and a handler declared as @RequestBody CreateOrder order throws "Required request body is missing". If the body is genuinely optional, say so:

java
@PostMapping("/preview")
Preview preview(@RequestBody(required = false) CreateOrder order) { ... }

Cause 2: the JSON is malformed

A trailing comma, a single-quoted string or a comment fails. Validate the payload with a tool before blaming the server; jq . payload.json prints the first syntax error. Sending a JSON body from a shell with the wrong quoting is the most common way to produce malformed JSON in a bug report.

Cause 3: a value has the wrong type

A field declared int receiving "abc", or a LocalDate receiving "14/03/2026", fails. For dates, use ISO 8601 (2026-03-14) or annotate the field with @JsonFormat(pattern = "dd/MM/yyyy"). If the error mentions LocalDate and a missing module, see the Jackson date fix.

Cause 4: an unknown enum value

java
enum Status { OPEN, PAID, SHIPPED }

A client sending "paid" in lower case fails by default. Either ask the client to send the constant name, or make the mapping case-insensitive in Spring Boot with spring.jackson.mapper.accept-case-insensitive-enums=true.

Return a clear error to the client

The default response body for a 400 is thin. Handle the exception and say what is wrong without leaking internals:

java
@ExceptionHandler(HttpMessageNotReadableException.class)
ProblemDetail unreadable(HttpMessageNotReadableException e) {
    ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.BAD_REQUEST, "The request body is missing or is not valid JSON.");
    problem.setTitle("Unreadable request");
    return problem;
}

Do not echo e.getMessage() to clients. It can contain class names and internals, which help an attacker and confuse a legitimate client.

Lenient and strict reading of unknown fields

Boot configures Jackson to ignore properties it does not know, so a client that adds a field is not rejected. That is a deliberate default and it hides typos: a client that sends emial instead of email gets a 200 and a null email. For an API where a wrong field name is a client bug, turn on strictness:

properties
spring.jackson.deserialization.fail-on-unknown-properties=true

With it on, the same request returns a 400 with Unrecognized field "emial" and the list of known properties. The change is strict for every endpoint, and a client that sends extra fields on purpose starts failing. Roll it out to an internal API first, or apply @JsonIgnoreProperties(ignoreUnknown = true) to the DTOs that have to stay lenient.

Dates and times

A date sent as "2026-03-14" into a LocalDate works, as the Java time module is registered by Boot. The same date sent as "14/03/2026" fails with Text '14/03/2026' could not be parsed at index 0, wrapped in the message. Declare the format on the field, or standardise on ISO 8601 across the API:

java
public record Booking(
        @JsonFormat(pattern = "dd/MM/yyyy") LocalDate date,
        int guests) { }

A timestamp sent as a number into an Instant is read as seconds with a fraction by default, and a client that sends milliseconds gets a date in the year 50,000. Agree on one convention, and write it in the API description.

Pin the behaviour with a test

The response to a bad body is part of the API, and a test keeps it stable:

java
@WebMvcTest(BookingController.class)
class BookingControllerTest {

    @Autowired
    MockMvc mvc;

    @Test
    void malformedJsonReturns400() throws Exception {
        mvc.perform(post("/bookings")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("{\"date\": \"not-a-date\", \"guests\": 2}"))
           .andExpect(status().isBadRequest());
    }

    @Test
    void emptyBodyReturns400() throws Exception {
        mvc.perform(post("/bookings").contentType(MediaType.APPLICATION_JSON))
           .andExpect(status().isBadRequest());
    }
}

Both cases arrive as this exception. Having them as tests means a later change to the handler, or to the Jackson configuration, cannot quietly turn them into 500 errors.

A response that helps the client fix the request

The default message includes Jackson's internal text and sometimes class names. Map the exception to a short, stable body, and keep the detail in the log:

java
@ExceptionHandler(HttpMessageNotReadableException.class)
ProblemDetail onUnreadable(HttpMessageNotReadableException e) {
    Throwable cause = e.getMostSpecificCause();
    ProblemDetail p = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
    p.setTitle("Request body could not be read");
    p.setDetail(cause instanceof JsonProcessingException j ? j.getOriginalMessage() : "Invalid JSON");
    return p;
}

getOriginalMessage omits the source location, which shows the position of the error in the client's own body and nothing about the server. Avoid echoing the whole cause to the client, since it can reveal field and class names that make the next guess easier.

How it differs from nearby errors

Status and exceptionMeaning
400 HttpMessageNotReadableExceptionThe body could not be parsed into the target type
400 MethodArgumentNotValidExceptionThe body parsed and failed Bean Validation
415 HttpMediaTypeNotSupportedExceptionThe Content-Type header is not one the endpoint consumes
406 HttpMediaTypeNotAcceptableExceptionThe client's Accept header cannot be satisfied
405 HttpRequestMethodNotSupportedExceptionThe path exists and the method does not

A client that forgets the Content-Type header gets a 415 and not this error, which saves time when the log shows no parse error at all.

Logging the rejected body safely

A 400 without the body is hard to investigate, and logging every body is a risk. A middle path logs a bounded, redacted version only for rejected requests. A filter or an advice that catches this exception can record the first 500 characters of the body with sensitive fields masked, along with the request id and the content type. The size limit protects the log from huge payloads, and the masking keeps passwords and tokens out of it.

Keep the log at a level that is not shipped to long-term storage, and keep it for days and not for months. The goal is to let a developer see what the client really sent, since the description in a support ticket is usually not the bytes on the wire.

Where this does not apply

If a body fails validation after it was read successfully, you get [MethodArgumentNotValidException](/library/methodargumentnotvalidexception-fix-return-clean-errors) instead. A 415 means the content type was the problem, not the content: [HttpMediaTypeNotSupportedException](/library/httpmediatypenotsupportedexception-fix-spring-mvc). The Spring MVC reference on message conversion lists the converters Spring Boot registers. The Spring MVC reference documents the behavior in detail.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.