Chapter 7

JSON in Java

Using Jackson library for JSON processing

Introduction to Jackson

Java requires a third-party library to process JSON, and Jackson is a popular choice:

💡 Maven Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.15.2</version>
</dependency>

Basic Usage

Object to JSON

ObjectMapper mapper = new ObjectMapper();
User user = new User("John Doe", 30);
String json = mapper.writeValueAsString(user);
// {"name":"John Doe","age":30}

JSON to Object

String json = "{\"name\":\"Jane Smith\",\"age\":28}";
User user = mapper.readValue(json, User.class);
System.out.println(user.getName());
// Jane Smith
🛠️

Productivity Booster

Not sure if the backend API JSON structure is correct? Don't just rely on logs, verify it with a tool for peace of mind.

👉 Online JSON Validator

Spring Boot Automatic Conversion

Spring Boot automatically handles JSON conversion:

@RestController
public class UserController {
  @GetMapping("/users")
  public List getUsers() {
    return Arrays.asList(
      new User("John Doe", 30),
      new User("Jane Smith", 28)
    );
  }
}