JSON Processing with Jackson
When you build REST APIs, data is usually sent and received as JSON (JavaScript Object Notation). It is lightweight, easy to read, and language-independent.
Spring uses Jackson library internally to convert Java objects to JSON and vice versa. You don't need to write any code – it happens automatically!
Spring uses Jackson library internally to convert Java objects to JSON and vice versa. You don't need to write any code – it happens automatically!
How it works:
- When you return a Java object from a @RestController method, Jackson automatically converts it to JSON.
- When you use @RequestBody, Jackson converts incoming JSON to a Java object.
Here is a simple example:
public class User {
private int id;
private String name;
private String email;
private LocalDate birthDate;
// constructors, getters, setters
}
@RestController
public class UserController {
@GetMapping("/user")
public User getUser() {
return new User(1, "John Doe", "john@example.com", LocalDate.of(1990, 1, 1));
}
}
When you call GET /user, you get JSON:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"birthDate": "1990-01-01"
}
Customizing JSON with Jackson Annotations:
public class User {
@JsonIgnore
private String password; // This field won't appear in JSON
@JsonProperty("full_name")
private String name; // In JSON, it appears as "full_name"
@JsonFormat(pattern = "dd-MM-yyyy")
private LocalDate birthDate; // Date formatted as 01-01-1990
@JsonInclude(JsonInclude.Include.NON_NULL)
private String phone; // If phone is null, it won't appear
}
Handling Dates:
By default, Java 8 dates (LocalDate, LocalDateTime) are serialized as arrays. To get proper format, add this in application.properties:
spring.jackson.date-format=yyyy-MM-dd
spring.jackson.serialization.write-dates-as-timestamps=false
Two Minute Drill
- Jackson automatically converts Java objects to JSON and vice versa.
- @JsonIgnore excludes fields from JSON.
- @JsonProperty changes field name in JSON.
- @JsonFormat customizes date formats.
- Configure global JSON settings in application.properties.
Need more clarification?
Drop us an email at career@quipoinfotech.com
