JSON to Java
Generate Java POJO classes from JSON
JSON Input
Java Output
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.
JSON to Java Use Cases
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 Type | Example | Java Type | Alternative |
|---|---|---|---|
| string | "hello" | String | String |
| number (integer) | 42 | int | int / Integer |
| number (float) | 3.14 | double | double / Double |
| boolean | true | boolean | boolean / Boolean |
| null | null | Object | Object (or @Nullable String) |
| object | {"k": "v"} | NestedClass | Record (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.
| Annotation | Purpose | Library |
|---|---|---|
| @JsonProperty("name") | Maps a JSON key to a Java field with a different name | Jackson |
| @SerializedName("name") | Same as @JsonProperty, but for the Gson library | Gson |
| @JsonIgnoreProperties | Ignores unknown JSON keys during deserialization instead of failing | Jackson |
| @Nullable | Marks a field as accepting null values from JSON input | JSR 305 / JetBrains |
| @NotNull | Enforces that a field must not be null, throws on violation | Bean Validation |
| @JsonFormat(pattern=...) | Defines a date/time format for serialization and deserialization | Jackson |
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.
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.
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
}// 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;
// }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;
# }# 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