Java Jackson JSON Array Example

1. Introduction

Working with JSON arrays is a common task when dealing with JSON data structures. Jackson, a popular Java library for JSON processing, provides a straightforward approach to handling JSON arrays, enabling developers to convert lists or arrays to/from JSON effortlessly. In this post, we will walk through a basic example of converting a list of Java objects to a JSON array and vice versa.

2. Example Steps

1. Set up your Java project with the required Jackson dependency.

2. Create a Java POJO (Plain Old Java Object) that will represent individual items in the array.

3. Use Jackson's ObjectMapper class to serialize a list of Java objects to a JSON array.

4. Deserialize the JSON array back into a list of Java objects.

5. Display the results.

3. Java Jackson JSON Array Example

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.List;

public class JacksonJsonArrayExample {

    public static class Product {
        public String name;
        public double price;

        public Product() {}  // Default constructor for deserialization

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

        @Override
        public String toString() {
            return "Product{name='" + name + "', price=" + price + "}";
        }
    }

    public static void main(String[] args) {
        try {
            // Create a list of products
            List<Product> products = Arrays.asList(
                new Product("Laptop", 1200.99),
                new Product("Mouse", 25.75),
                new Product("Keyboard", 49.50)
            );

            // Create ObjectMapper instance
            ObjectMapper objectMapper = new ObjectMapper();

            // Serialize list of products to JSON array
            String jsonArray = objectMapper.writeValueAsString(products);
            System.out.println("JSON Array: " + jsonArray);

            // Deserialize JSON array back to list of products
            List<Product> deserializedProducts = objectMapper.readValue(jsonArray, new TypeReference<List<Product>>(){});
            System.out.println("Deserialized Products: " + deserializedProducts);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output:

JSON Array: [{"name":"Laptop","price":1200.99},{"name":"Mouse","price":25.75},{"name":"Keyboard","price":49.5}]
Deserialized Products: [Product{name='Laptop', price=1200.99}, Product{name='Mouse', price=25.75}, Product{name='Keyboard', price=49.5}]

4. Step By Step Explanation

1. We first define a simple Product class representing items that we want in our JSON array. It has fields name and price.

2. The main method initializes a list of Product objects which we aim to convert to a JSON array.

3. We instantiate Jackson's ObjectMapper which will facilitate the conversion.

4. Using the writeValueAsString method of the ObjectMapper, we serialize our list of products to a JSON array.

5. To deserialize the JSON array back to a list of Product objects, we use the readValue method of the ObjectMapper. Notice the use of TypeReference which helps in specifying that we want a list of Product objects.

6. Both the serialized JSON array and the deserialized list of products are printed to the console.

By leveraging the power of Jackson, we can easily handle conversions between Java collections and JSON arrays.


Comments