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

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.jsonschema2pojo:jsonschema2pojo-gradle-plugin:1.1.1")
    }
}

JSON Schema Input

We will use this sample JSON.

{
  "type": "object",
  "properties": {
    "firstName": {
      "type": "string"
    },
    "lastName": {
      "type": "string"
    },
    "age": {
      "type": "number"
    }
  }
}

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.

plugins {
    java
    id("jsonschema2pojo")
}

Configuration

Basic configuration to get started. See more here.

jsonSchema2Pojo {
    targetDirectory = file("$buildDir/generated-sources/js2p")
    targetPackage = "io.thewokecoder.pojo"
    generateBuilders = true
    includeAdditionalProperties = false
    setSource(files("$projectDir/src/main/resources/json"))
    setAnnotationStyle("none")
}

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.