JSON to Java

Generate Java POJO classes from JSON

Try an example
Root class name:

JSON Input

Java Output

Runs locally Β· Safe to paste secrets
Java classes will appear here…

What is JSON to Java Class Conversion?

JSON to Java class conversion takes a raw JSON object and produces Plain Old Java Object (POJO) definitions with private fields, getters, and setters. Java has no built-in JSON type system, so every JSON API response, config file, or message payload needs a corresponding class before you can work with it in a type-safe way. Libraries like Jackson and Gson map JSON keys to Java fields through reflection, but they require the class definitions to exist first.

A standard Java POJO for JSON deserialization declares a private field for each JSON key, a no-argument constructor, and a getter/setter pair per field. Nested JSON objects become separate classes. Arrays become List<T> fields with a java.util.List import. Primitive JSON types map to Java primitives (int, double, boolean) or their wrapper types (Integer, Double, Boolean) when used inside generics. Null values typically map to Object or a nullable reference type.

Writing these class definitions by hand is repetitive. You read each JSON key, determine the Java type from the value, convert naming conventions from camelCase JSON to camelCase Java fields, create PascalCase class names for nested objects, and add the getter/setter boilerplate. For a JSON object with 15 fields and 3 nested objects, that means writing 4 classes, 30+ methods, and keeping everything consistent. A converter does this in milliseconds.

Why Use a JSON to Java Converter?

Manually creating Java POJOs from JSON means inspecting each field, inferring types from sample values, writing getter/setter pairs, and repeating the process for every nested object. When the API contract changes, you update everything by hand. A converter removes that mechanical work.

⚑
Instant POJO generation
Paste your JSON and get complete Java class definitions in under a second. Nested objects, lists, and primitive types are detected and mapped automatically.
πŸ”’
Privacy-first processing
Conversion runs entirely in your browser using JavaScript. Your JSON data never leaves your machine. API keys, tokens, and production data stay private.
πŸ“
Correct type inference
Every generated field uses the appropriate Java type inferred from the JSON value: String, int, double, boolean, List<T>, or Object for nulls. Wrapper types are used inside generics.
πŸ“¦
No install or signup
Open the page and paste your JSON. No JDK, no Maven dependencies, no account. Works on any device with a browser.

JSON to Java Use Cases

Spring Boot API Development
Generate request and response DTOs from API JSON samples. Paste the expected payload shape and get Java classes ready for @RequestBody and @ResponseBody annotations in Spring controllers.
Android App Development
Create model classes for Retrofit or Volley network responses. Paste the JSON returned by your backend API and get POJOs compatible with Gson or Moshi converters.
Microservice Integration
Define typed message classes for Kafka, RabbitMQ, or gRPC JSON payloads. Paste a sample message and generate POJOs that document the expected contract between services.
Legacy System Migration
Convert JSON API responses into Java classes when wrapping REST endpoints in a typed client. Useful when migrating from loosely-typed Map<String, Object> patterns to proper domain models.
QA and Test Automation
Build typed test fixtures from API response samples. QA engineers can paste real JSON responses and produce POJO definitions for use in JUnit or TestNG test suites with AssertJ assertions.
Learning Java OOP Patterns
Students can paste any JSON structure and see how Java represents it with classes, fields, getters, setters, and nested types. The output makes it concrete rather than abstract.

JSON to Java Type Mapping

Every JSON value maps to a specific Java type. The table below shows how the converter translates each JSON type into its Java equivalent. The Alternative column shows wrapper types used inside generic contexts like List<T>, or newer Java features like Records.

JSON TypeExampleJava TypeAlternative
string"hello"StringString
number (integer)42intint / Integer
number (float)3.14doubledouble / Double
booleantruebooleanboolean / Boolean
nullnullObjectObject (or @Nullable String)
object{"k": "v"}NestedClassRecord (Java 16+)
array of strings["a", "b"]List<String>List<String>
array of objects[{"id": 1}]List<Item>List<Item>
mixed array[1, "a"]List<Object>List<Object>

Java JSON Annotation Reference

When deserializing JSON with Jackson or Gson, annotations control how JSON keys map to Java fields, how unknown fields are handled, and how null values are treated. This reference covers the annotations you will encounter most often when working with generated POJOs.

AnnotationPurposeLibrary
@JsonProperty("name")Maps a JSON key to a Java field with a different nameJackson
@SerializedName("name")Same as @JsonProperty, but for the Gson libraryGson
@JsonIgnorePropertiesIgnores unknown JSON keys during deserialization instead of failingJackson
@NullableMarks a field as accepting null values from JSON inputJSR 305 / JetBrains
@NotNullEnforces that a field must not be null, throws on violationBean Validation
@JsonFormat(pattern=...)Defines a date/time format for serialization and deserializationJackson

POJO vs Record vs Lombok

Java has three common approaches for defining typed structures to hold JSON data. Each fits a different project style and Java version. POJOs are the traditional pattern with the widest compatibility. Records reduce boilerplate for immutable data. Lombok generates getters, setters, and constructors at compile time via annotations.

POJO
Traditional Java pattern. Works with Java 8+. You define private fields plus getter/setter methods. Full control over mutability and custom logic. Compatible with every JSON library (Jackson, Gson, Moshi). The standard choice for Spring Boot, Android, and enterprise codebases.
Record (Java 16+)
Built-in since Java 16 (preview in 14). Compact syntax: record User(int id, String name) generates constructor, accessors, equals, hashCode, and toString. Instances are immutable. Jackson supports records from version 2.12. Best for value objects and DTOs where you do not need setters.
Lombok @Data
Third-party compile-time annotation processor. @Data generates getters, setters, equals, hashCode, and toString. @Builder adds a builder pattern. Reduces boilerplate to near-record levels while keeping mutability. Requires adding Lombok to your build tool (Maven/Gradle) and IDE plugin.

Code Examples

These examples show how to use generated Java POJOs with Jackson for deserialization, how to produce Java classes programmatically from JavaScript and Python, and how to use the jsonschema2pojo CLI tool for batch generation.

Java (Jackson deserialization)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    private int id;
    private String name;
    private String email;
    private boolean active;
    private double score;
    private Address address;
    private List<String> tags;

    // getters and setters omitted for brevity

    public static void main(String[] args) throws Exception {
        String json = "{\"id\":1,\"name\":\"Alice\",\"email\":\"alice@example.com\",\"active\":true,\"score\":98.5,\"address\":{\"street\":\"123 Main St\",\"city\":\"Springfield\",\"zip\":\"12345\"},\"tags\":[\"admin\",\"user\"]}";
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(json, User.class);
        System.out.println(user.getName()); // -> Alice
    }
}

class Address {
    private String street;
    private String city;
    private String zip;
    // getters and setters
}
JavaScript (generate Java POJO from JSON)
// Minimal JSON-to-Java-POJO generator in JS
function jsonToJava(obj, name = "Root") {
  const classes = [];
  function infer(val, fieldName) {
    if (val === null) return "Object";
    if (typeof val === "string") return "String";
    if (typeof val === "number") return Number.isInteger(val) ? "int" : "double";
    if (typeof val === "boolean") return "boolean";
    if (Array.isArray(val)) {
      const first = val.find(v => v !== null);
      if (!first) return "List<Object>";
      const elem = infer(first, fieldName);
      const boxed = elem === "int" ? "Integer" : elem === "double" ? "Double" : elem === "boolean" ? "Boolean" : elem;
      return `List<${boxed}>`;
    }
    if (typeof val === "object") {
      const cls = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
      build(val, cls);
      return cls;
    }
    return "Object";
  }
  function build(obj, cls) {
    const fields = Object.entries(obj).map(([k, v]) => {
      const type = infer(v, k);
      return `    private ${type} ${k};`;
    });
    classes.push(`public class ${cls} {\n${fields.join("\n")}\n}`);
  }
  build(obj, name);
  return classes.join("\n\n");
}

console.log(jsonToJava({ id: 1, name: "Alice", scores: [98, 85] }, "User"));
// public class User {
//     private int id;
//     private String name;
//     private List<Integer> scores;
// }
Python (generate Java classes from JSON)
import json

def json_to_java(obj: dict, class_name: str = "Root") -> str:
    classes = []

    def infer(val, name):
        if val is None:
            return "Object"
        if isinstance(val, bool):
            return "boolean"
        if isinstance(val, int):
            return "int"
        if isinstance(val, float):
            return "double"
        if isinstance(val, str):
            return "String"
        if isinstance(val, list):
            if not val:
                return "List<Object>"
            elem = infer(val[0], name)
            boxed = {"int": "Integer", "double": "Double", "boolean": "Boolean"}.get(elem, elem)
            return f"List<{boxed}>"
        if isinstance(val, dict):
            cls = name[0].upper() + name[1:]
            build(val, cls)
            return cls
        return "Object"

    def build(obj, cls):
        fields = [f"    private {infer(v, k)} {k};" for k, v in obj.items()]
        classes.append(f"public class {cls} {{\n" + "\n".join(fields) + "\n}")

    build(obj, class_name)
    return "\n\n".join(classes)

data = json.loads('{"id": 1, "name": "Alice", "tags": ["admin"]}')
print(json_to_java(data, "User"))
# public class User {
#     private int id;
#     private String name;
#     private List<String> tags;
# }
CLI (jsonschema2pojo)
# Install jsonschema2pojo (requires Java 8+)
# Download from https://github.com/joelittlejohn/jsonschema2pojo

# Generate POJOs from a JSON file
jsonschema2pojo --source user.json --target src/main/java \
  --source-type json --annotation-style jackson2

# Generate with Gson annotations instead
jsonschema2pojo --source user.json --target src/main/java \
  --source-type json --annotation-style gson

# From a JSON string via stdin
echo '{"id": 1, "name": "Alice", "tags": ["admin"]}' | \
  jsonschema2pojo --source-type json --annotation-style jackson2 \
  --target src/main/java --target-package com.example.model

Frequently Asked Questions

What is the difference between a POJO and a Java Bean?
A POJO (Plain Old Java Object) is any simple Java class with no framework dependencies. A Java Bean is a POJO that follows specific conventions: a no-argument constructor, private fields with public getters and setters, and implements Serializable. For JSON mapping, most libraries require Bean conventions (getters/setters) but do not require Serializable. The classes generated by this tool follow the Bean getter/setter pattern.
Which JSON library should I use with generated POJOs?
Jackson (com.fasterxml.jackson) is the most widely used Java JSON library and the default in Spring Boot. Gson (com.google.gson) is popular in Android projects and has a simpler API. Moshi is a newer alternative from Square, designed for Kotlin interoperability. All three work with standard POJOs that have getters and setters.
How does the converter handle nested JSON objects?
Each nested object becomes a separate Java class. If a JSON field named "address" contains an object with "street" and "city" keys, the converter creates an Address class with those fields and types the parent field as Address. Deeply nested structures produce multiple class definitions.
What happens when a JSON field is null?
Null fields are typed as Object because the converter cannot infer the intended type from a null value alone. In practice, you would replace Object with the expected type (String, Integer, etc.) once you know the API contract. If using Jackson, null values are assigned to reference-type fields by default without errors.
Should I use Java Records instead of POJOs for JSON?
Records work well for immutable data transfer objects where you do not need setters. Jackson supports records from version 2.12, and Gson added support in later releases. If your project runs on Java 16+ and you treat API responses as read-only data, records reduce boilerplate. If you need mutability or target Java 8/11, stick with POJOs.
How do I handle JSON keys that are not valid Java identifiers?
JSON keys like "first-name" or "2nd_place" are not valid Java field names. Use @JsonProperty("first-name") in Jackson or @SerializedName("first-name") in Gson to map the JSON key to a valid Java field name like firstName. The converter automatically converts key names to camelCase Java fields.
Can I generate Java classes from a JSON Schema instead of a JSON sample?
This tool generates classes from JSON data samples. For JSON Schema input, use the jsonschema2pojo project (available as a CLI tool, Maven plugin, and Gradle plugin). It reads a JSON Schema file and produces annotated Java classes with validation constraints, default values, and documentation from the schema descriptions.