Generate POJOs From JSON Schema With Gradle
Introduction
In this article, we will demonstrate how to generate Java classes, also called POJOs, using JSON files. This is made easier by using a handy library called jsonschema2pojo.
Setup
We are going to be using Gradle as our build tool because it is fast, flexible and easy to learn. We will also be using the Kotlin DSL because of type checking and auto-completion.
We will include the jsonschema2pojo Gradle Plugin as a buildscript dependency because it is only available in maven central.
Add this to your settings.gradle.kts
JSON Schema Input
We will use this sample JSON.
Common mapping from JSON schema type to Java types.
Schema type | Java type |
---|---|
string |
java.lang.String |
number |
java.lang.Double |
integer |
java.lang.Integer |
boolean |
java.lang.Boolean |
object |
generated Java type |
array |
java.util.List |
array (with “uniqueItems”:true) |
java.util.Set |
any |
java.lang.Object |
Apply The Plugin
Note that we can omit the version number as we have added it in our build classpath during the setup.
Configuration
Basic configuration to get started. See more here.
Then build your project, and see the generated classes in the build directory.
Conclusion
In some situations, auto generating POJOs from JSON schema can be really useful.
You can find complete working code here.