1. Jackson `ObjectMapper` (Spring Boot Default)

Jackson is the standard JSON library bundled inside Spring Boot starters. Its core class, `ObjectMapper`, handles high-speed POJO serialization and deserialization.

Jackson POJO Serialization Example
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;

public class JacksonDemo {
    public static class User {
        @JsonProperty("user_id")
        private long id;
        
        @JsonProperty("full_name")
        private String name;

        public User(long id, String name) { this.id = id; this.name = name; }
        // Getters and setters omitted for brevity
    }

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(404, "Duke Java");

        // Pretty print JSON string
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
        System.out.println(json);
    }
}
Explanation: `@JsonProperty` maps Java camelCase fields to snake_case JSON keys.

2. Google Gson (`GsonBuilder`)

Google Gson is a lightweight, intuitive library popular in Android applications and standalone Java utilities for its simple API (`gson.toJson()` and `gson.fromJson()`).

Gson Object Serialization Example
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonDemo {
    public static class Product {
        @SerializedName("product_sku")
        private String sku;
        private double price;

        public Product(String sku, double price) { this.sku = sku; this.price = price; }
    }

    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Product laptop = new Product("LAP-991", 1299.99);

        String jsonOutput = gson.toJson(laptop);
        System.out.println(jsonOutput);
    }
}
Explanation: `GsonBuilder().setPrettyPrinting()` creates human-readable indented JSON output.

3. Jackson vs Gson Performance Benchmarks

In benchmark tests with large JSON payloads (> 10 MB), Jackson outperforms Gson by 2x to 3x in parsing throughput due to Jackson's low-level streaming parser (`JsonParser`). However, Gson has a smaller memory footprint (~300 KB library size), making it ideal for Android or lightweight serverless JARs.

Pro Tips

  • Reuse `ObjectMapper` and `Gson` instances as singleton beans to avoid costly instantiation overhead.
  • Use Jackson's `@JsonIgnore` or Gson's `transient` keyword to hide sensitive password fields.