0
0
Spring Bootframework~5 mins

JSON serialization with Jackson in Spring Boot

Choose your learning style9 modes available
Introduction

Jackson helps convert Java objects into JSON format easily. This lets your app send data in a way other programs understand.

When you want to send Java objects as JSON in a web API response.
When saving Java objects as JSON files for configuration or storage.
When you need to log Java object data in JSON format for easier reading.
When integrating with frontend apps that expect JSON data.
When debugging by quickly viewing object data as JSON.
Syntax
Spring Boot
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(yourObject);
Use writeValueAsString() to convert an object to a JSON string.
Jackson automatically converts fields of your Java object into JSON keys and values.
Examples
Converts a simple Person object to JSON string.
Spring Boot
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Person("Alice", 30));
Enables pretty printing to make JSON output easier to read.
Spring Boot
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(new Person("Bob", 25));
Serializes a list of strings into a JSON array.
Spring Boot
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(List.of("apple", "banana", "cherry"));
Sample Program

This program creates a Person object and uses Jackson's ObjectMapper to convert it to a nicely formatted JSON string. It then prints the JSON.

Spring Boot
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.List;

public class JsonExample {
    public static class Person {
        public String name;
        public int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

    public static void main(String[] args) throws Exception {
        Person person = new Person("John", 28);
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        String json = mapper.writeValueAsString(person);
        System.out.println(json);
    }
}
OutputSuccess
Important Notes

Jackson uses public fields or getters to find data to serialize.

You can customize JSON output with annotations like @JsonProperty or by configuring ObjectMapper.

Remember to handle exceptions because serialization can fail if objects are not compatible.

Summary

Jackson converts Java objects to JSON strings easily.

Use ObjectMapper and writeValueAsString() for serialization.

Enable pretty print with SerializationFeature for readable JSON output.