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

How do I convert array into JSON?

In the example below you can see how to convert an array into JSON string. We serialize the array to JSON using the Gson.toJson() method. To deserialize a string of JSON into array we use the Gson.fromJson() method.

package org.kodejava.gson;

import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // Create a new instance of Gson
        Gson gson = new Gson();

        // Convert numbers array into JSON string.
        String numbersJson = gson.toJson(numbers);

        // Convert strings array into JSON string
        String daysJson = gson.toJson(days);

        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        // Convert from JSON string to a primitive array of int.
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int number : fibonacci) {
            System.out.print(number + " ");
        }
        System.out.println();

        // Convert from JSON string to a string array.
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (String weekDay : weekDays) {
            System.out.print(weekDay + " ");
        }
        System.out.println();

        // Converting multidimensional array into JSON
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        // Convert JSON string into multidimensional array of int.
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int[] i : dataMap) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

Here is our code result:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13 
Sun Mon Tue Wed Thu Fri Sat 
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3 
3 4 5 
4 5 6

Maven Dependencies

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

Maven Central