JSON Schema to POJO: Enterprise Contract-First
Stop guessing structure. Define your API with a JSON Schema contract and generate robust, validated Java classes automatically.
The Standard: jsonschema2pojo
In the enterprise, we don't paste JSON into websites. We use build plugins. The gold standard is jsonschema2pojo.
What is jsonschema2pojo? It is a build tool (Maven/Gradle) that reads your schema.json source of truth and automatically generates Java POJOs with JSR-303 validation and Jackson annotations during the build process.
Maven
<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<configuration>
<sourceDirectory>src/main/resources/schema</sourceDirectory>
<targetPackage>com.example.types</targetPackage>
</configuration>
</plugin>
Gradle
plugins {
id "org.jsonschema2pojo" version "1.2.1"
}
jsonSchema2Pojo {
targetPackage = 'com.example.types'
useLongIntegers = true
}Enforcing Validation (JSR-303)
A schema isn't just structure; it's rules. By enabling JSR-303, your generated POJOs will include standard validation annotations.
// Schema Property
"email": {
"type": "string",
"format": "email",
"minLength": 5
}
// Generated Java
@NotNull
@Size(min = 5)
@Pattern(regexp = "...")
public String email;
Config Tip: Ensure includeJsr303Annotations is set to true in your build config.
Handling "OneOf" Polymorphism
JSON Schema oneOf allows a field to be a User OR a Company. Java handles this through Interfaces and Jackson Polymorphism.
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes({
@Type(value = User.class, name = "user"),
@Type(value = Company.class, name = "company")
})
public interface Actor { ... }
Modern Dates (Java 8)
Don't get stuck with java.util.Date. Force the generator to use modern java.time types.
// Gradle Config
customDateType = "java.time.LocalDate"
customDateTimeType = "java.time.LocalDateTime"
Reducing Boilerplate (Lombok)
Generated POJOs can be extremely verbose. While jsonschema2pojo doesn't strictly depend on Lombok, you can configure it to be cleaner:
- Set
includeConstructors = truefor easier instantiation. - Set
includeHashcodeAndEquals = truefor Value Object semantics. - Or, generated the source to a separate folder and let your IDE collapse it.
Contract-First vs. Code-First
| Feature | JSON Schema (Contract) | Raw JSON (Code) |
|---|---|---|
| Source of Truth | The Schema File | The Java Class |
| Validation | Strict (JSR-303) | Manual |
Need a Quick POJO?
If you don't have a 500-line Schema and just want to convert a JSON snippet, use our instant converter.
Convert JSON to POJO Instantly