Generate Java class from JSON? Generate Java class from JSON? json json

Generate Java class from JSON?


Try http://www.jsonschema2pojo.org

Or the jsonschema2pojo plug-in for Maven:

<plugin>    <groupId>org.jsonschema2pojo</groupId>    <artifactId>jsonschema2pojo-maven-plugin</artifactId>    <version>1.0.2</version>    <configuration>        <sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>        <targetPackage>com.myproject.jsonschemas</targetPackage>        <sourceType>json</sourceType>    </configuration>    <executions>        <execution>            <goals>                <goal>generate</goal>            </goals>        </execution>    </executions></plugin>

The <sourceType>json</sourceType> covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.

Updated in 2014: Two things have happened since Dec '09 when this question was asked:

  • The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules

  • I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

Hope this helps!


If you're using Jackson (the most popular library there), try

https://github.com/astav/JsonToJava

Its open source (last updated on Jun 7, 2013 as of year 2021) and anyone should be able to contribute.

Summary

A JsonToJava source class file generator that deduces the schema based on supplied sample json data and generates the necessary java data structures.

It encourages teams to think in Json first, before writing actual code.

Features

  • Can generate classes for an arbitrarily complex hierarchy (recursively)
  • Can read your existing Java classes and if it can deserialize into those structures, will do so
  • Will prompt for user input when ambiguous cases exist


Here's an online tool that will take JSON, including nested objects or nested arrays of objects and generate a Java source with Jackson annotations.