How do I use JSON libraries like Jackson or Gson in modern Java?

In modern Java, using JSON libraries like Jackson or Gson is the standard way to handle data exchange, as the Java Standard Library does not include a built-in JSON parser.

With Java 25, you can take advantage of Records for clean data models and Text Blocks for readable JSON strings in your code.

1. Using Jackson (Industry Standard)

Jackson is highly recommended for modern applications, especially within the Spring and Jakarta EE ecosystems.

Maven Dependency:

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

Code Example:

import com.fasterxml.jackson.databind.ObjectMapper;

// 1. Define a Record (Modern Java way)
public record User(Long id, String name) {}

public class JacksonDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // Serialization (Object to JSON)
        User user = new User(1L, "Duke");
        String json = mapper.writeValueAsString(user);
        System.out.println("JSON: " + json);

        // Deserialization (JSON to Object)
        String inputJson = """
                {
                    "id": 2,
                    "name": "Java"
                }
                """;
        User decodedUser = mapper.readValue(inputJson, User.class);
        System.out.println("User Name: " + decodedUser.name());
    }
}

2. Using Gson (Google’s Library)

Gson is known for its simplicity and ease of use for smaller projects or quick utilities.

Maven Dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

Code Example:

import com.google.code.gson.Gson;
import com.google.code.gson.GsonBuilder;

public class GsonDemo {
    public static void main(String[] args) {
        // Use GsonBuilder for custom configurations like Pretty Printing
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // Serialization
        User user = new User(10L, "Modern Java");
        String json = gson.toJson(user);
        System.out.println(json);

        // Deserialization
        User fromJson = gson.fromJson(json, User.class);
        System.out.println("ID from JSON: " + fromJson.id());
    }
}

Key Comparisons & Tips

  • Records Support: Both Jackson (2.12+) and Gson (2.10+) support Java Records natively. This is the preferred way to create POJOs for data mapping.
  • Immutability: Since Records are immutable, these libraries use reflection or canonical constructors to populate the data, which is much safer than traditional setter-based beans.
  • Performance: Jackson is generally faster and offers more features for complex mapping (like @JsonProperty for renaming fields).
  • Integration: If you are using Spring Boot, Jackson is already included and configured for you.

Integrating with HttpClient

When fetching data from an API using the java.net.http.HttpClient, you typically receive a String which you then pass to these libraries:

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
User user = mapper.readValue(response.body(), User.class);

For more advanced use cases, you can even write a custom BodyHandler that uses Jackson to parse the stream directly, saving memory on large JSON payloads.

How do I Parse JSON Responses from Java 11 HttpClient Easily?

To parse JSON responses easily using Java 11’s HttpClient, you can use libraries like Jackson or Gson that help in converting a JSON string to Java objects (POJOs) without hassle.

Here’s a step-by-step guide:

Step 1: Create a Java 11 HttpClient request

  1. Use Java’s HttpClient to make an HTTP request and get the JSON response as a string.
  2. Use HttpRequest or HttpResponse as part of the Java 11 HttpClient API.

Step 2: Add Jackson or Gson to Parse JSON

  1. Jackson: Add the dependency to your pom.xml (for Maven):
    <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <version>2.15.2</version> 
    </dependency>
    
  2. Gson: Add this dependency:
    <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.10.1</version> 
    </dependency>
    

Step 3: Example Using Jackson

package org.kodejava.net.http;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class HttpClientJacksonExample {

    public static void main(String[] args) throws Exception {
        // 1. Create an HttpClient
        HttpClient client = HttpClient.newHttpClient();

        // 2. Create an HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("https://jsonplaceholder.typicode.com/posts/1")) // Example URL
                .GET()
                .build();

        // 3. Send the HttpRequest and get an HttpResponse
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 4. Parse JSON String Response to a Java Object using Jackson
        ObjectMapper mapper = new ObjectMapper();
        Post post = mapper.readValue(response.body(), Post.class);

        // 5. Use the parsed object
        System.out.println("Post Title: " + post.getTitle());
    }

    // Sample POJO to match the JSON structure
    public static class Post {
        private int userId;
        private int id;
        private String title;
        private String body;

        // Getters and Setters
        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }
    }
}

Step 4: Example Using Gson

package org.kodejava.net.http;

import com.google.gson.Gson;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class HttpClientGsonExample {

    public static void main(String[] args) throws Exception {
        // 1. Create HttpClient
        HttpClient client = HttpClient.newHttpClient();

        // 2. Create HttpRequest
        HttpRequest request = HttpRequest.newBuilder()
                .uri(new URI("https://jsonplaceholder.typicode.com/posts/1")) // Example URL
                .GET()
                .build();

        // 3. Send HttpRequest and get HttpResponse
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 4. Parse JSON String response to Java Object using Gson
        Gson gson = new Gson();
        Post post = gson.fromJson(response.body(), Post.class);

        // 5. Use the parsed object
        System.out.println("Post Title: " + post.getTitle());
    }

    // Sample POJO class to match the JSON structure
    public static class Post {
        private int userId;
        private int id;
        private String title;
        private String body;

        // Getters and Setters
        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getBody() {
            return body;
        }

        public void setBody(String body) {
            this.body = body;
        }
    }
}

Key Points:

  • Serialization and Deserialization: POJO structure must match your JSON’s keys.
  • Why Jackson or Gson?
    They are robust and simplify working with JSON (and even converting nested structures).

How do I pretty-print JSON string in Google Gson?

In the following example you’ll see how to format JSON string using the Google Gson library. Here are the steps:

  • We create a Map.
  • Put a couple key-value pairs to it. We put a string, a LocalDate object and an array of String[].
  • Create a Gson object using the GsonBuilder. This allows us to configure the Gson object.
  • We use the setPrettyPrinting() to configure Gson to output pretty print.
  • The registerTypeAdapter() allows us to register custom serializer, in this case we use it to serialize LocalDate object.

Here is our code snippet:

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GsonPrettyPrint {
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "Duke");
        map.put("address", "Menlo Park");
        map.put("dateOfBirth", LocalDate.of(2000, Month.FEBRUARY, 1));
        map.put("languages", new String[]{"Java", "Kotlin", "JavaScript"});

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .registerTypeAdapter(LocalDate.class, new LocaleDateAdapter())
                .create();
        String json = gson.toJson(map);
        System.out.println(json);
    }

    static class LocaleDateAdapter implements JsonSerializer<LocalDate> {
        @Override
        public JsonElement serialize(LocalDate date, Type type, JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(date.format(DateTimeFormatter.ISO_DATE));
        }
    }
}

Running this code produces the following result:

{
  "address": "Menlo Park",
  "languages": [
    "Java",
    "Kotlin",
    "JavaScript"
  ],
  "name": "Duke",
  "dateOfBirth": "2000-02-01"
}

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

Maven Central

How do I convert Map into JSON?

This example show you how to convert a java.util.Map into JSON string and back to Map again.

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        // Convert a Map into JSON string.
        Gson gson = new Gson();
        String json = gson.toJson(colours);
        System.out.println("json = " + json);

        // Convert JSON string back to Map.
        Type type = new TypeToken<Map<String, String>>() {
        }.getType();
        Map<String, String> map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
    }
}

Here is the result of the program:

json = {"RED":"#FF0000","WHITE":"#FFFFFF","BLUE":"#0000FF","BLACK":"#000000","YELLOW":"#FFFF00","GREEN":"#008000"}
map.get = #FF0000
map.get = #FFFFFF
map.get = #0000FF
map.get = #000000
map.get = #FFFF00
map.get = #008000

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

Maven Central

How do I convert collections into JSON?

This example show you how to convert Java collections object into JSON string. For Student class use in this example you can find it the previous example on How do I convert object into JSON?.

package org.kodejava.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.kodejava.gson.support.Student;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CollectionToJson {
    public static void main(String[] args) {
        // Converts a collection of string object into JSON string.
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);

        // Converts a collection Student object into JSON string
        Student a = new Student("Alice", "Apple St", getDOB(2000, 10, 1));
        Student b = new Student("Bob", "Banana St", null);
        Student c = new Student("Carol", "Grape St", getDOB(2000, 5, 21));
        Student d = new Student("Mallory", "Mango St", null);

        List<Student> students = new ArrayList<>();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);

        // Converts JSON string into a collection of Student object.
        Type type = new TypeToken<List<Student>>() {
        }.getType();
        List<Student> studentList = gson.fromJson(jsonStudents, type);

        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
        }
    }

    private static Date getDOB(int year, int month, int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DATE, date);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
}

Here is the result of our program:

jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Oct 1, 2000, 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"May 21, 2000, 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory

Maven Dependencies

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.11.0</version>
</dependency>

Maven Central