Handling JSON with Jackson in Spring Boot

JSON (JavaScript Object Notation) is the most widely used data format in REST APIs. Spring Boot, by default, uses Jackson as its JSON library to serialize Java objects to JSON and deserialize JSON into Java objects.

In this post, we’ll explore how Jackson works with Spring Boot, how to customize the JSON behavior, and best practices for working with JSON in your application.

Handling JSON with Jackson in Spring Boot

πŸ”§ Jackson in Spring Boot

Spring Boot automatically includes Jackson dependencies through spring-boot-starter-web. This makes Jackson the default JSON processor.

✨ Key features of Jackson:

  • Object to JSON and JSON to Object conversion
  • Annotations for custom mappings
  • Support for nested objects, collections, maps, etc.

βœ… Basic Setup

1. Add Spring Web Dependency

If you’re using Maven:



    org.springframework.boot
    spring-boot-starter-web

Jackson is included transitively in spring-boot-starter-web.

πŸ§ͺ JSON Input Example: POST API

Let’s create a simple REST API that accepts a JSON payload.

πŸ“ Model Class: User.java


package com.kscodes.springboot.jsondemo.model;

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

    // Getters and setters
    // toString() for logging
}

πŸ“‚ Controller: UserController.java


package com.kscodes.springboot.jsondemo.controller;

import com.kscodes.springboot.jsondemo.model.User;
import org.springframework.web.bind.annotation.*;

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

    @PostMapping
    public String createUser(@RequestBody User user) {
        // Jackson converts JSON to User object
        return "User created: " + user.toString();
    }
}

🧾 Sample JSON Input


{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com"
}

πŸ“€ JSON Output Example: GET API

You can also return Java objects as JSON.

πŸ” Extend the Controller



@GetMapping("/{name}")
public User getUser(@PathVariable String name) {
    // Simulate user data
    User user = new User();
    user.setName(name);
    user.setAge(25);
    user.setEmail(name.toLowerCase() + "@example.com");
    return user;
}

Spring Boot automatically converts the User object to JSON using Jackson.

πŸ› οΈ Customizing JSON with Jackson Annotations

1. @JsonProperty – Change JSON property name


@JsonProperty("user_name")
private String name;

2. @JsonIgnore – Ignore field in JSON


@JsonIgnore
private String password;

3. @JsonInclude – Exclude null or default values


@JsonInclude(JsonInclude.Include.NON_NULL)
private String email;

πŸ“¦ Handling Nested JSON


public class Address {
    private String city;
    private String country;
}

public class User {
    private String name;
    private Address address;
}

Jackson will automatically map nested JSON like:


{
  "name": "Alice",
  "address": {
    "city": "Mumbai",
    "country": "India"
  }
}

πŸ”„ Convert Objects Manually (Optional)

Sometimes you may need to convert manually.

Inject ObjectMapper


@Autowired
private ObjectMapper objectMapper;

Convert Object to JSON


String json = objectMapper.writeValueAsString(user);

Convert JSON to Object


User user = objectMapper.readValue(json, User.class);

πŸ§ͺ Testing the APIs with Postman or curl

POST


curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Jane","age":28,"email":"jane@example.com"}'

GET


curl http://localhost:8080/api/users/Jane

βš™οΈ Customize ObjectMapper Globally

You can define a custom ObjectMapper bean to control serialization globally.


@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    return mapper;
}

🧰 Common Pitfalls

IssueSolution
JSON parse errorCheck if @RequestBody is used and all fields match
Null values in responseUse @JsonInclude(Include.NON_NULL)
Extra fields ignoredEnable mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

πŸ“š External References

πŸ“Œ Conclusion

Spring Boot and Jackson provide an out-of-the-box solution for JSON handling. You can start building JSON APIs with almost no configuration. For advanced needs, Jackson annotations and ObjectMapper customization give you full control over serialization and deserialization.