DEV Community

Anh Trần Tuấn
Anh Trần Tuấn

Posted on • Originally published at tuanh.net on

Reasons Your JSON Data Is Null When Sent via Postman in Spring Boot (and How to Fix It)

1. Understanding the Problem

When sending JSON data to a Spring Boot controller, encountering null values indicates that the framework could not correctly deserialize your JSON payload into the expected object. Several factors could cause this:

1.1 Missing @RequestBody Annotation

Spring Boot requires explicit annotations to map incoming JSON to Java objects. Forgetting to annotate the method parameter with @RequestBody is a common reason for this issue.

Example : Missing @RequestBody

@RestController
@RequestMapping("/api")
public class UserController {

    @PostMapping("/create")
    public ResponseEntity<String> createUser(User user) { // Missing @RequestBody
        return ResponseEntity.ok("User created: " + user.getName());
    }
}
Enter fullscreen mode Exit fullscreen mode

Sending this request in Postman:

{
    "name": "John",
    "age": 25
}
Enter fullscreen mode Exit fullscreen mode

The user object will be null, leading to unexpected behavior.

1.2 Incorrect Content-Type Header

Spring Boot uses the Content-Type header to determine how to parse the incoming payload. If the Content-Type header is not set to application/json, the framework may not recognize the payload.

1.3 Mismatched Field Names in JSON and Java

Java objects require exact field names that match the JSON keys. Even a minor mismatch can result in null values during deserialization.

Example: Field Name Mismatch

Java Class:

public class User {
    private String name;
    private int age;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Payload sent via Postman:

{
    "username": "John",
    "age": 25
}
Enter fullscreen mode Exit fullscreen mode

In this case, name will be null because the key username doesn’t match any field in the User class.

2. Solutions to Fix Null JSON Data

2.1 Adding @RequestBody Annotation

To resolve the issue of missing @RequestBody, simply add it to the controller method parameter.

Fixed Example:

@RestController
@RequestMapping("/api")
public class UserController {

    @PostMapping("/create")
    public ResponseEntity<String> createUser(@RequestBody User user) {
        return ResponseEntity.ok("User created: " + user.getName());
    }
}
Enter fullscreen mode Exit fullscreen mode

This tells Spring Boot to deserialize the incoming JSON payload into the User object.

2.2 Setting the Correct Content-Type Header

Ensure the request sent from Postman includes the Content-Type header with a value of application/json.

How to Do This in Postman:

  • In the request tab, navigate to the "Headers" section.
  • Add a header:
    • Key : Content-Type
    • Value : application/json
  • Send the request.

2.3 Using @JsonProperty for Mismatched Field Names

If the field names in the JSON payload don’t match the Java object, use the @JsonProperty annotation to specify the mapping.

Example:

public class User {
    @JsonProperty("username")
    private String name;
    private int age;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Now, sending this JSON:

{
    "username": "John",
    "age": 25
}
Enter fullscreen mode Exit fullscreen mode

Will correctly map username to name.

3. Expanding the Discussion

3.1 Common Errors in JSON Deserialization

Sometimes, errors are more complex, such as nested objects or arrays in JSON. These require proper mapping in your Java classes.

Example: Nested JSON

JSON Payload:

{
    "name": "John",
    "age": 25,
    "address": {
        "city": "New York",
        "zipcode": "10001"
    }
}
Enter fullscreen mode Exit fullscreen mode

Java Classes:

public class User {
    private String name;
    private int age;
    private Address address;

    // Getters and Setters
}

public class Address {
    private String city;
    private String zipcode;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Ensure the structure of your Java classes matches the nested JSON format.

3.2 Validating Input Data

Spring Boot provides validation annotations to ensure incoming JSON is valid. Use @valid along with the @RequestBody annotation and define validation constraints.

Example:

import jakarta.validation.constraints.NotNull;

public class User {
    @NotNull(message = "Name cannot be null")
    private String name;

    private int age;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Controller:

@PostMapping("/create")
public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
    return ResponseEntity.ok("User created: " + user.getName());
}
Enter fullscreen mode Exit fullscreen mode

Invalid JSON will return a descriptive error response automatically.

3.3 Debugging and Testing

When encountering issues, debugging is critical. Add breakpoints in your IDE or log the incoming payload for inspection.

Example:

@PostMapping("/create")
public ResponseEntity<String> createUser(@RequestBody User user) {
    System.out.println("Received user: " + user);
    return ResponseEntity.ok("User created: " + user.getName());
}
Enter fullscreen mode Exit fullscreen mode

4. Preventing Similar Issues

Using API Documentation Tools

Leverage tools like Swagger or Postman collections to ensure consistent testing and documentation of API payloads.

Automating Tests

Integrate tools like JUnit and MockMVC to test your endpoints programmatically and catch deserialization issues early.

Example:

@Test
public void testCreateUser() throws Exception {
    String userJson = "{"name":"John", "age":25}";

    mockMvc.perform(post("/api/create")
        .contentType(MediaType.APPLICATION_JSON)
        .content(userJson))
        .andExpect(status().isOk())
        .andExpect(content().string(containsString("John")));
}
Enter fullscreen mode Exit fullscreen mode

5. Conclusion

Handling null JSON data when sending requests through Postman to a Spring Boot application is often straightforward once the underlying causes are understood. By ensuring proper annotations, setting the correct headers, and using validation, you can avoid many pitfalls. Expanding your understanding to include debugging and testing practices will further solidify your API’s robustness.

If you have any questions or specific scenarios you’d like to discuss, feel free to comment below. Let’s resolve these issues together!

Read posts more at : Reasons Your JSON Data Is Null When Sent via Postman in Spring Boot (and How to Fix It)

Top comments (0)