← Back to list

Spring Boot: Fixing HttpMessageNotReadableException — Cannot map null values into type int

If you’ve ever encountered this error while creating a REST API in Spring Boot, you’re not alone.

Dattatray Bodake · 2026-07-19 07:39 · 0 claps · 4.4 min read
#spring-boot #exception-handling #wrapper-class
Open on Medium ↗
Wiki topics: 🎵 · Music & Audio

Spring Boot: Fixing HttpMessageNotReadableException — Cannot map null values into type int

If you’ve ever encountered this error while creating a REST API in Spring Boot, you’re not alone.

One of the most common JSON deserialization issues occurs when Jackson tries to map a null value into a Java primitive type.

In this article, we’ll understand:

  • The error
  • Why it happens
  • How Jackson deserializes JSON
  • Multiple solutions
  • Best practices
  • Common interview questions

The Error

While sending a POST request to a Postman from Spring Boot API: @POSTMAPPING /addProduct

The application returned the following response:

{

“timestamp”: “2026–03–31T11:22:43.914Z”,

“status”: 400,

“error”: “Bad Request”,

“trace”: “org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot map null into type int (set DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES to ‘false’ to allow)”,

“message”: “JSON parse error: Cannot map null into type int (set DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES to ‘false’ to allow)”,

“path”: “/addProduct”

}

The Request That Caused It

The client sent:

{

“id”: null,

“name”: “Laptop”,

“category”: “Electronics”,

“description”: “Gaming Laptop”,

“price”: 75000

}

Meanwhile, the entity looked like this:

private int id;

Jackson attempted to perform:

null → int

Since Java primitive types cannot hold null, deserialization failed before the controller method was even invoked.

Why Does This Happen?

Spring Boot uses Jackson to convert incoming JSON into Java objects.

During deserialization:

{

“id”: null

}

Jackson tries to assign : int id = null;

But Java primitives have default values only after object creation — they cannot receive null.

Primitive types:

Type

Can hold null?

int

❌ No

long

❌ No

double

❌ No

boolean

❌ No

Wrapper classes:

Type

Can hold null?

Integer

✅ Yes

Long

✅ Yes

Double

✅ Yes

Boolean

✅ Yes

Solution 1 (Recommended): Use Wrapper Classes

Instead of:

private int id;

Use:

private Integer id;

Why?

  • Supports null
  • Better suited for database entities
  • Works perfectly with JPA auto-generated IDs.

Solution 2: Do Not Send id in Create Requests

If your entity uses:

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

The database generates the ID automatically.

Your @POSTMAPPING request should be:

{

“name”: “Laptop”,

“category”: “Electronics”,

“description”: “Gaming Laptop”,

“price”: 75000

}

Notice there is no id field.

This is the recommended REST API design.

Solution 3: Disable Jackson’s Strict Check (Not Recommended)

Jackson provides this configuration:

objectMapper.configure(

DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,

false

);

Now,

“id”: null

Becomes

id = 0;

Although this prevents the exception, it can introduce subtle bugs because 0 may be interpreted as a valid identifier.

Use this option only when you fully understand its implications.

Solution 4: Validate Input Explicitly

If the ID must never be null:

@NotNull

private Integer id;

Validation provides clearer error messages and avoids silent failures.

A Hidden Problem: Constructor + Primitive Mismatch

Many developers fix the field type but still encounter the same exception.

Consider this entity:

private Integer id;

But the constructor is:

public Product(

int id,

String name,

String category,

String description,

int price

)

The field is correct.

The constructor is not.

When Jackson uses this constructor, it still tries to perform:

null → int

Result:

HttpMessageNotReadableException

Incorrect Entity

@Entity

public class Product {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

private String name;

private String category;

private String description;

private Integer price;

public Product(int id, String name, String category, String description, int price) {

this.id = id;

this.name = name;

this.category = category;

this.description = description;

this.price = price;

}

}

The problem is the constructor parameters:

int id

int price

Correct Entity

@Entity

@Table(name = “product2”)

public class Product {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

@Column(name = “prod_name”)

private String name;

@Column(name = “prod_category”)

private String category;

@Column(name = “prod_description”)

private String description;

@Column(name = “prod_price”)

private Integer price;

public Product() {

}

public Product(String name, String category, String description, Integer price) {

this.name = name;

this.category = category;

this.description = description;

this.price = price;

}

// Getters and Setters

}

Notice:

  • No id parameter
  • Wrapper types
  • Default constructor

Constructor Rules for Spring Boot Entities

Rule 1: Always provide a no-argument constructor

Jackson requires it for object creation.

public Product() {}

Rule 2: Do not include auto-generated IDs in constructors

Avoid:

public Product(Integer id, …)

Prefer:

public Product(String name, String category, Integer price)

Rule 3: Avoid primitive parameters

Instead of:

int price

Use:

Integer price

This allows Jackson to safely map missing or null values.

Rule 4: Let JPA manage identifiers

If using:

@GeneratedValue

never manually populate the ID in create requests.

Best Practices

✅ Use wrapper classes (Integer, Long, Double, Boolean) in JPA entities.

✅ Never send auto-generated IDs in POST requests.

✅ Always include a default constructor.

✅ Keep constructors focused on business data, not persistence details.

✅ Use Bean Validation (@NotNull, @NotBlank, @Positive) for input validation.

✅ Prefer DTOs over exposing entity classes directly in REST APIs.

Before vs After

Before

Request:

{

“id”: null,

“name”: “Laptop”

}

Entity:

private int id;

Result:

400 Bad Request

Cannot map null into type int

After

Request:

{

“name”: “Laptop”

}

Entity:

private Integer id;

Result:

201 Created

Common Interview Questions

1. Why can’t Java primitive types store null?

Primitive types (int, double, boolean) represent raw values and are not objects. Since null represents the absence of an object reference, primitives cannot hold it.

2. Why are wrapper classes preferred in JPA entities?

Wrapper classes:

  • Support null
  • Work better with database columns
  • Allow optional fields
  • Avoid Jackson deserialization errors

3. Why shouldn’t we send id in POST requests?

Because the database generates it using: @GeneratedValue

The client shouldn’t control primary key values.

4. What is HttpMessageNotReadableException?

It is thrown when Spring cannot deserialize the incoming HTTP request body into a Java object, often due to malformed JSON or type mismatches.

5. What does Jackson do in Spring Boot?

Jackson converts:

  • JSON → Java Objects (Deserialization)
  • Java Objects → JSON (Serialization)

6. Why is a default constructor required?

Jackson first creates an object using the no-argument constructor and then populates its fields. Without it (or without a suitable creator), deserialization may fail.

7. Why is FAIL_ON_NULL_FOR_PRIMITIVES disabled by some developers?

It allows null values to become default primitive values (such as 0 for int). While this prevents exceptions, it can hide data quality issues and should generally be avoided.

Final Takeaways

This error isn’t caused by Spring Boot itself — it’s the result of a mismatch between JSON input and Java types during Jackson deserialization.

To build robust REST APIs:

  • Use wrapper classes (Integer instead of int) for nullable fields.
  • Avoid including auto-generated IDs in create requests.
  • Provide a no-argument constructor.
  • Keep constructors free of persistence-managed fields like IDs.
  • Validate incoming requests with Bean Validation.
  • Consider using dedicated DTOs instead of exposing JPA entities directly.

Following these practices will help you avoid common deserialization issues and produce cleaner, more maintainable Spring Boot applications.

Suggested SEO Title

Spring Boot: Fix “Cannot map null into type int” (HttpMessageNotReadableException) — Complete Guide with Examples

Suggested Medium Tags

  • Spring Boot
  • Java
  • REST API
  • Jackson
  • JPA
  • Hibernate
  • Backend Development
  • Software Engineering

Suggested Stack Overflow Article Title

Why Spring Boot Throws HttpMessageNotReadableException: Cannot map null into type int and How to Fix It


메타데이터
post_id
191e9fc85aec
slug
spring-boot-fixing-httpmessagenotreadableexception-cannot-map-null-values-into-type-int-191e9fc85aec
url
https://medium.com/@dattatraybodake/spring-boot-fixing-httpmessagenotreadableexception-cannot-map-null-values-into-type-int-191e9fc85aec
canonical_url
https://medium.com/@dattatraybodake/spring-boot-fixing-httpmessagenotreadableexception-cannot-map-null-values-into-type-int-191e9fc85aec
author_url
https://medium.com/@dattatraybodake
status
ok
fetched_at
2026-08-26 09:11:53