Explain Codes LogoExplain Codes Logo

Generate Java class from JSON?

java
json-serialization
jackson-library
java-annotations
Nikita BarsukovbyNikita Barsukov·Feb 8, 2025
TLDR

Quickly generate a Java class from a JSON by using the jsonschema2pojo online tool. Insert your JSON to the tool, adjust settings including package and class names, then click on "Generate" to download your Java files.

On top of that, the Jackson library provides a programmatic approach, where one can derive Java classes from JSON using ObjectMapper and JsonSchemaGenerator:

ObjectMapper mapper = new ObjectMapper(); JsonSchema schema = new JsonSchemaGenerator(mapper).generateSchema(YourClass.class); String schemaAsString = mapper.writeValueAsString(schema); // That's how easy it is to order a JSONSchema from ObjectMapper "Starbucks"! ;)

If you want a chocolaty Maven topping, integrate the jsonschema2pojo-maven-plugin for automated Java class generation through your build process:

<plugin> <groupId>org.jsonschema2pojo</groupId> <artifactId>jsonschema2pojo-maven-plugin</artifactId> <version>1.1.1</version> <configuration> <sourceType>json</sourceType> <sourceDirectory>${project.basedir}/src/main/resources</sourceDirectory> <targetPackage>com.example.generated</targetPackage> </configuration> <executions> <execution> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin>

ObjectMapper for conversion

Jackson's ObjectMapper can do just more than parsing JSON objects - it can be used to define the structure of Java classes as well:

ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonInput); JavaType javaType = mapper.getTypeFactory().constructType(MyClass.class); mapper.convertValue(jsonNode, javaType); // Custom-made class, extra fresh, straight from the Jackson kitchen!

Exploiting annotations

By using Jackson annotations, the generation of classes can be automated, and data retrieval methods effectively configured:

@JsonDeserialize(builder = Cake.Builder.class) public class Cake { // Annotated fields... // You woke up in the matrix, and chose to bake a Cake class! @JsonPOJOBuilder }

Customize the feast

In case of more complex scenarios, Jackson offers custom deserializers where you retain your reins but expand your control:

class CustomDeserializer extends StdDeserializer<MyClass> { // Override methods to handle deserialization... // Sometimes you just gotta take the extra mile to make the MyClass of your dreams. }

Mastering jsonschema2pojo

Command line commando

Fans of the terminal can count on the jsonschema2pojo command-line interface for a more direct route to Java class creation:

jsonschema2pojo --source "/path/to/json" --target "/path/to/output" --package "com.example" // Let's get down to business, to defeat the bugs!

Maven integration

Enhance your Maven workflow by integrating the jsonschema2pojo plugin in your pom.xml to have classes automatically generated during your build:

<!-- Maven plugin configuration shown in Fast Answer --> // "This ain't a scene, it's a Maven build process" - Fall out Boy (probably)

Advanced user features

Utilize the advanced functionalities of jsonschema2pojo to successfully handle arrays, nested objects, and apply inheritance in your class definitions:

{ "type": "object", "properties": { "list": { "type": "array", "items": { "$ref": "CommonItem.json" } } // Robust definitions for nested objects and other complexities... } }

Open source community engagement

Unfolding GitHub secrets

Deep dive into the jsonschema2pojo GitHub repository, contribute to its development, engage with the community, and uncover its potential:

- Resolve potential issues by browsing the discussion threads. - Examine pull requests for recent enhancements and updates. - Star and watch the repository to stay updated on recent changes.

Open source project integration

Extend beyond jsonschema2pojo by considering other open source projects such as JsonToJava, which can also deduce schemas from JSON whilst generating rich Java class hierarchies:

- Consider `JsonToJava` for a different way to generate classes. - Push the boundaries and constraints of supported JSON features. - Your contributions can improve these tools for the benefit of the entire community.