JSON in Java

Java does not include built-in JSON support, but several powerful libraries make JSON handling straightforward. The most popular ones are Jackson and Gson. Java developers use JSON heavily in REST APIs, Android apps, and enterprise applications.

Popular Java JSON Libraries

Think of JSON libraries as translators. Java objects speak Java. JSON speaks a universal language. A library acts as the translator between the two.

  • Jackson — The most widely used. Fast, feature-rich, used in Spring Boot by default.
  • Gson — Created by Google. Simple to use, good for Android development.
  • org.json — Lightweight, good for small projects without complex object mapping.

Setting Up Gson (Maven)

Add this dependency to your pom.xml file:

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

Setting Up Jackson (Maven)

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

Converting Java Object to JSON (Serialization)

Serialization means turning a Java object into a JSON string. This is what you do when you want to send data to an API or save it to a file.

Step 1: Create a Java Class

public class Product {
    private int id;
    private String name;
    private double price;
    private boolean inStock;

    // Constructor
    public Product(int id, String name, double price, boolean inStock) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.inStock = inStock;
    }

    // Getters (required by Gson and Jackson)
    public int getId() { return id; }
    public String getName() { return name; }
    public double getPrice() { return price; }
    public boolean isInStock() { return inStock; }
}

Step 2: Convert to JSON Using Gson

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

public class Main {
    public static void main(String[] args) {
        Product product = new Product(101, "Wireless Keyboard", 1299.99, true);

        // Create Gson with pretty printing
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // Convert Java object to JSON string
        String json = gson.toJson(product);
        System.out.println(json);
    }
}

Output

{
  "id": 101,
  "name": "Wireless Keyboard",
  "price": 1299.99,
  "inStock": true
}

Converting JSON to Java Object (Deserialization)

Deserialization means turning a JSON string back into a Java object. This is what you do when you receive data from an API.

Using Gson

import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        String json = "{\"id\":101,\"name\":\"Wireless Keyboard\",\"price\":1299.99,\"inStock\":true}";

        Gson gson = new Gson();

        // Convert JSON string to Java object
        Product product = gson.fromJson(json, Product.class);

        System.out.println(product.getName());   // Wireless Keyboard
        System.out.println(product.getPrice());  // 1299.99
        System.out.println(product.isInStock()); // true
    }
}

Diagram: Serialization and Deserialization

SERIALIZATION (Java to JSON)
------------------------------
Java Object (Product)
    |
    v
gson.toJson(product)
    |
    v
JSON String: {"id":101,"name":"Wireless Keyboard",...}

DESERIALIZATION (JSON to Java)
------------------------------
JSON String: {"id":101,"name":"Wireless Keyboard",...}
    |
    v
gson.fromJson(json, Product.class)
    |
    v
Java Object (Product) with all fields filled

Working with JSON Arrays in Java

Array of Objects to JSON

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product(101, "Wireless Keyboard", 1299.99, true));
        products.add(new Product(102, "USB Hub", 599.00, false));

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(products);
        System.out.println(json);
    }
}

Output

[
  {
    "id": 101,
    "name": "Wireless Keyboard",
    "price": 1299.99,
    "inStock": true
  },
  {
    "id": 102,
    "name": "USB Hub",
    "price": 599.0,
    "inStock": false
  }
]

JSON Array to Java List

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String json = "[{\"id\":101,\"name\":\"Wireless Keyboard\",\"price\":1299.99,\"inStock\":true}]";

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Product>>(){}.getType();
        List<Product> products = gson.fromJson(json, listType);

        for (Product p : products) {
            System.out.println(p.getName());
        }
    }
}

Using Jackson for JSON in Java

Jackson is the default JSON library in Spring Boot. It works similarly to Gson but with different method names.

Serialize with Jackson

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        Product product = new Product(101, "Wireless Keyboard", 1299.99, true);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(product);
        System.out.println(json);
    }
}

Deserialize with Jackson

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) throws Exception {
        String json = "{\"id\":101,\"name\":\"Wireless Keyboard\",\"price\":1299.99,\"inStock\":true}";

        ObjectMapper mapper = new ObjectMapper();
        Product product = mapper.readValue(json, Product.class);

        System.out.println(product.getName());
    }
}

Handling Nested JSON in Java

// Nested class structure
public class Order {
    private int orderId;
    private Product product;
    private int quantity;

    // Getters and setters...
}
String json = "{\"orderId\":5001,\"product\":{\"id\":101,\"name\":\"Wireless Keyboard\",\"price\":1299.99,\"inStock\":true},\"quantity\":2}";

Gson gson = new Gson();
Order order = gson.fromJson(json, Order.class);

System.out.println(order.getOrderId());              // 5001
System.out.println(order.getProduct().getName());    // Wireless Keyboard
System.out.println(order.getQuantity());             // 2

Reading a JSON File in Java

import com.google.gson.Gson;
import java.io.FileReader;

public class Main {
    public static void main(String[] args) throws Exception {
        Gson gson = new Gson();
        FileReader reader = new FileReader("product.json");
        Product product = gson.fromJson(reader, Product.class);
        reader.close();
        System.out.println(product.getName());
    }
}

Common Errors in Java JSON Handling

Error: JsonSyntaxException

Thrown when the JSON string has invalid syntax. Check for missing commas, unclosed brackets, or unquoted keys.

Error: Fields Not Mapped

If your JSON has a key that does not match any field in your Java class, Gson and Jackson simply ignore it by default. This is useful when APIs return extra fields you do not need.

Error: No-Arg Constructor Missing

Jackson requires a default (no-argument) constructor to deserialize JSON. Add one to your class if you see a related error.

Gson vs Jackson Comparison

Feature               Gson              Jackson
-------               ----              -------
Setup complexity      Simple            Moderate
Speed                 Good              Faster for large data
Spring Boot default   No                Yes
Android use           Very common       Less common
Annotation support    Limited           Extensive

Summary

Java handles JSON through libraries like Gson and Jackson. Gson is simple and great for Android. Jackson is faster and integrates directly with Spring Boot. Both libraries convert Java objects to JSON strings (serialization) and JSON strings back to Java objects (deserialization). Nested objects, arrays, and file reading are all supported with minimal code.

Leave a Comment

Your email address will not be published. Required fields are marked *