Best examples of Java JSON processing examples for modern apps

If you work with APIs, microservices, or cloud backends, you live and breathe JSON. Theory is fine, but what developers actually search for are clear, working examples of Java JSON processing examples they can drop straight into a project. This guide focuses on exactly that: real examples, not vague descriptions. We’ll walk through several example of JSON processing in Java using the libraries that actually show up in production code: Jackson, Gson, org.json, JSON-B/Jakarta EE, and JsonPath. These examples include parsing HTTP responses, mapping JSON to POJOs, streaming very large payloads, validating JSON, and handling tricky edge cases like unknown fields and null handling. Along the way, we’ll talk about 2024–2025 trends, such as record classes, Java 21, and why Jackson still dominates the Java JSON ecosystem. By the end, you’ll have a set of the best examples of Java JSON processing examples you can adapt for REST APIs, event-driven systems, and everyday backend tasks.
Written by
Jamie
Published

Let’s start where most developers start: you have a JSON string and you need to do something practical with it. The following examples of Java JSON processing examples use Jackson, because it’s still the workhorse in Spring Boot and most enterprise stacks.

Example of parsing a simple JSON string with Jackson

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SimpleJsonParseExample {
    public static void main(String[] args) throws Exception {
        String json = "{"name":"Alice","age":30,"active":true}";

        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(json);

        String name = root.get("name").asText();
        int age = root.get("age").asInt();
        boolean active = root.get("active").asBoolean();

        System.out.printf("User %s is %d years old, active=%b%n", name, age, active);
    }
}

This is one of the best examples for beginners: short, readable, and it shows how to navigate a JSON tree.


POJO mapping: the best examples for real-world APIs

Most modern Java apps don’t want to poke around JSON trees forever. Instead, they map JSON to POJOs. These examples include record classes and Lombok-style models that you’re likely using in 2024–2025.

Example of mapping JSON to a Java record (Java 17+)

import com.fasterxml.jackson.databind.ObjectMapper;

public class RecordMappingExample {

    public record User(String id, String email, boolean verified) {}

    public static void main(String[] args) throws Exception {
        String json = "{"id":"u-123","email":"user@example.com","verified":true}";

        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);

        System.out.println(user.email());
    }
}

This example of record mapping works nicely with Spring Boot 3 and Java 21, which are steadily becoming the default in greenfield projects.

Example of mapping JSON arrays to Java collections

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;

public class JsonArrayExample {
    public static void main(String[] args) throws Exception {
        String json = "[{"id":1,"name":"A"},{"id":2,"name":"B"}]";

        ObjectMapper mapper = new ObjectMapper();

        List<Item> items = mapper.readValue(json, new TypeReference<List<Item>>() {});

        items.forEach(i -> System.out.println(i.getName()));
    }

    public static class Item {
        private int id;
        private String name;

        // getters and setters omitted for brevity
    }
}

Real examples like this show how you’d handle a typical REST API response returning a list of objects.


Streaming and large payloads: examples of Java JSON processing examples at scale

If you’re ingesting logs, telemetry, or big data feeds, you can’t just load everything into memory. These examples of Java JSON processing examples use Jackson’s streaming API to keep memory usage under control.

Example of streaming a large JSON array from an InputStream

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

import java.io.FileInputStream;
import java.nio.file.Path;

public class StreamingJsonExample {
    public static void main(String[] args) throws Exception {
        JsonFactory factory = new JsonFactory();

        try (FileInputStream fis = new FileInputStream(Path.of("events.json").toFile());
             JsonParser parser = factory.createParser(fis)) {

            if (parser.nextToken() != JsonToken.START_ARRAY) {
                throw new IllegalStateException("Expected JSON array");
            }

            while (parser.nextToken() == JsonToken.START_OBJECT) {
                String type = null;
                long timestamp = 0L;

                while (parser.nextToken() != JsonToken.END_OBJECT) {
                    String fieldName = parser.getCurrentName();
                    parser.nextToken();

                    switch (fieldName) {
                        case "type" -> type = parser.getText();
                        case "timestamp" -> timestamp = parser.getLongValue();
                        default -> parser.skipChildren();
                    }
                }

                System.out.printf("Event type=%s ts=%d%n", type, timestamp);
            }
        }
    }
}

For log pipelines or analytics systems, this is one of the best examples of Java JSON processing examples because it shows how to process millions of events without blowing up the heap.


Gson vs Jackson: lighter-weight examples for simple tasks

Gson is still common in Android and smaller utilities. The following examples include both reading and writing.

Example of parsing JSON into a POJO with Gson

import com.google.gson.Gson;

public class GsonParseExample {

    static class Product {
        String id;
        String name;
        double price;
    }

    public static void main(String[] args) {
        String json = "{"id":"p-1","name":"Coffee","price":3.99}";

        Gson gson = new Gson();
        Product product = gson.fromJson(json, Product.class);

        System.out.println(product.name + " costs $" + product.price);
    }
}

Example of serializing a Java object to JSON with Gson

import com.google.gson.Gson;

public class GsonWriteExample {
    public static void main(String[] args) {
        User user = new User("u-42", "user@example.com");
        Gson gson = new Gson();

        String json = gson.toJson(user);
        System.out.println(json);
    }

    record User(String id, String email) {}
}

These lighter-weight snippets are good examples of Java JSON processing examples when you need minimal configuration and you’re not in a Spring-heavy backend.


org.json and minimal dependencies: examples include quick parsing

Some legacy projects still use org.json. It’s not my favorite, but you’ll encounter it, so here is a practical example of how it looks.

Example of using org.json for quick parsing

import org.json.JSONObject;

public class OrgJsonExample {
    public static void main(String[] args) {
        String json = "{"status":"ok","count":5}";

        JSONObject obj = new JSONObject(json);
        String status = obj.getString("status");
        int count = obj.getInt("count");

        System.out.printf("Status=%s, count=%d%n", status, count);
    }
}

This example of parsing is typical in older codebases or small command-line tools where adding Jackson or Gson feels heavy.


JSON-B and Jakarta EE: standard-based examples of Java JSON processing examples

If you’re working in Jakarta EE or MicroProfile environments, JSON-B is the standard API for binding JSON to Java objects.

Example of JSON-B serialization and deserialization

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;

public class JsonbExample {

    public static class Customer {
        public String id;
        public String name;
    }

    public static void main(String[] args) {
        Jsonb jsonb = JsonbBuilder.create();

        Customer c = new Customer();
        c.id = "c-1";
        c.name = "Acme Corp";

        String json = jsonb.toJson(c);
        System.out.println(json);

        Customer back = jsonb.fromJson(json, Customer.class);
        System.out.println(back.name);
    }
}

For Jakarta EE 10+ apps, this is one of the best examples of Java JSON processing examples because it uses the standardized API that app servers support out of the box.


Querying JSON with JsonPath: examples include selective extraction

Sometimes you only need a couple of fields out of a large JSON document. JsonPath gives you an XPath-like syntax for JSON.

Example of using JsonPath to read nested fields

import com.jayway.jsonpath.JsonPath;

import java.util.List;

public class JsonPathExample {
    public static void main(String[] args) {
        String json = "{"store":{"book":[{"title":"Java","price":10.0},{"title":"Kotlin","price":12.5}]}}";

        List<String> titles = JsonPath.read(json, "$.store.book[*].title");
        Double maxPrice = JsonPath.read(json, "$.store.book[*].price.max()");

        System.out.println("Titles: " + titles);
        System.out.println("Max price: " + maxPrice);
    }
}

If you’re building monitoring tools, API gateways, or log processors, this is a very practical example of Java JSON processing examples that avoids full POJO mapping.


Validation and schema: examples of keeping JSON honest

In security-sensitive systems, you don’t just parse JSON; you validate it. While JSON Schema libraries are third-party, they’re widely used in enterprise environments.

Example of validating JSON against a JSON Schema (Everit-style)

import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;

public class JsonValidationExample {
    public static void main(String[] args) {
        String schemaStr = "{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]}";
        String jsonStr = "{"name":"Missing id"}";

        JSONObject rawSchema = new JSONObject(schemaStr);
        Schema schema = SchemaLoader.load(rawSchema);

        try {
            schema.validate(new JSONObject(jsonStr));
            System.out.println("Valid JSON");
        } catch (org.everit.json.schema.ValidationException e) {
            System.out.println("Validation errors: " + e.getAllMessages());
        }
    }
}

In regulated industries like healthcare and finance, real examples like this help teams enforce contracts between services. For context on data standards and interoperability in health data, the U.S. Office of the National Coordinator for Health Information Technology discusses JSON-based exchange formats in its interoperability resources at healthit.gov.


Dealing with unknown fields and nulls: defensive examples of Java JSON processing examples

Production JSON is messy. Fields appear and disappear, naming conventions drift, and sometimes you just need the parser not to explode.

Example of ignoring unknown JSON properties with Jackson

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;

public class IgnoreUnknownExample {

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class ApiResponse {
        public String status;
        public String message;
    }

    public static void main(String[] args) throws Exception {
        String json = "{"status":"ok","message":"done","extra":"ignored"}";

        ObjectMapper mapper = new ObjectMapper();
        ApiResponse response = mapper.readValue(json, ApiResponse.class);

        System.out.println(response.status);
    }
}

Example of custom null handling with Jackson

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

public class NullHandlingExample {

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public static class Profile {
        public String id;
        public String nickname; // may be null
    }

    public static void main(String[] args) throws Exception {
        Profile p = new Profile();
        p.id = "p-1";
        p.nickname = null;

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(p);

        // nickname will be omitted from JSON
        System.out.println(json);
    }
}

These defensive patterns show up in real examples from production microservices, where API contracts evolve over time.


A few patterns stand out in current examples of Java JSON processing examples:

  • Record classes and Java 21: More teams are switching from verbose POJOs to records, especially for request/response DTOs.
  • Spring Boot 3 and Jakarta EE 10+: These stacks push Jackson and JSON-B as first-class citizens, with auto-configuration and annotations.
  • Observability and security: JSON now powers logs, traces, and metrics. The OWASP Foundation provides guidance on secure JSON handling and injection risks at owasp.org.
  • Data exchange in health and research: JSON is heavily used in health APIs and research data exchange, with organizations such as the National Institutes of Health (nih.gov) publishing JSON-based datasets and tools.

If you understand the examples above, you’re in good shape for the next few years of backend and API development.


FAQ: short answers with real examples

Q: What are some simple examples of Java JSON processing examples for beginners?
A: The best starting point is a basic ObjectMapper.readTree example to parse a string into a JsonNode, plus a POJO mapping example using readValue. Add a small Gson snippet if you’re working on Android or a lightweight tool.

Q: Can you give an example of streaming JSON in Java for large files?
A: Use Jackson’s JsonParser with a FileInputStream, as shown in the streaming example above. Iterate token by token, process objects as you see START_OBJECT, and avoid loading the entire array into memory.

Q: Which library should I pick for most real examples in 2025?
A: For Spring Boot and most microservices, Jackson remains the default. In Jakarta EE and MicroProfile, JSON-B is standard. Gson works well for small utilities and Android, while JsonPath shines when you need to query large JSON blobs without full mapping.

Q: Are there examples of validating JSON before processing it?
A: Yes. The JSON Schema validation example with Everit shows how to load a schema and validate incoming JSON. This pattern is common in APIs that must enforce strict contracts, especially in sectors like healthcare and finance.

Q: How do I handle unknown or changing JSON fields safely?
A: In Jackson, annotate your model with @JsonIgnoreProperties(ignoreUnknown = true) or configure the ObjectMapper to ignore unknown properties. This keeps your code stable when upstream services add fields you don’t care about yet.

Explore More Java Code Snippets

Discover more examples and insights in this category.

View All Java Code Snippets