Effortlessly Convert JSON to Java Classes
Have you ever been in a position where you must implement Java classes based on JSON schemas send to you for your application?
Well, we all know converting JSON to Java classes can streamline our development process, especially when working with APIs or data interchange formats.
Whether you’re building a REST API client or handling complex data structures, having Java classes mirroring your JSON data can save you time and reduce errors.
Today we will explore 3 different ways you can easily create the corresponding class from your JSON schema.
1. DIY
First make sure you add the following dependency to your maven project:
<dependency>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-core</artifactId>
<version>1.1.1</version> <!-- Or another version that suits you -->
</dependency>
If you are not using maven you can manually find the dependency jar and add it your libs folder from here.
Below is the main code fragment that you will need.
try {
//Copy and paste your json String
String json = "{\n" +
" \"title\": \"New Blog Post\",\n" +
" \"content\": \"This is the content of the blog post...\",\n" +
" \"publishedDate\": \"2023-08-25T15:00:00Z\",\n" +
" \"author\": {\n" +
" \"username\": \"authoruser\",\n" +
" \"email\": \"[email protected]\"\n" +
" },\n" +
" \"tags\": [\"Technology\", \"Programming\"]\n" +
"}\n";
String outputDirectory = "/path/for/output"; //set your output path
String packageName = "com.jimchr.mypackage.generated"; //set the package name for the generated classes
String className = "TestResponse"; //set a class name for your base obj
ConvertJsonToJavaClass converter = new ConvertJsonToJavaClass();
converter.convertJsonStringToJavaClass(json, outputDirectory, packageName, className);
} catch (IOException e) {
e.printStackTrace();
}
Now the ConvertJsonToJavaClass:
public class ConvertJsonToJavaClass {
public void convertJsonStringToJavaClass(String jsonString, File outputJavaClassDirectory, String packageName, String javaClassName)
throws IOException {
JCodeModel jcodeModel = new JCodeModel();
MyJsonGeneratorConfig config = new MyJsonGeneratorConfig();
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(jcodeModel, javaClassName, packageName, jsonString);
jcodeModel.build(outputJavaClassDirectory);
}
public static class MyJsonGeneratorConfig extends DefaultGenerationConfig {
@Override
public boolean isGenerateBuilders() {
return true;
}
@Override
public SourceType getSourceType() {
return SourceType.JSON;
}
}
}
That’s it! You made it, now just run the code the way you want to and check the output directory for the generated classes.
2. Use my tool - JsonToJavaConverter
Because I found it hard to believe that someone would likely have this code inside their app I’ve decided to create a very small tool to streamline the process for created the java classes.
How to Use JsonToJavaConverter
- Clone the repository:
git clone https://gitlab.com/jimchr12/jsontojavaconverter.git
cd jsontojavaconverter
- Build the Project with maven:
mvn clean install
-
Run The Tool
Open up a terminal in the project path ( /your/path/to/jsontojavaconverter )
There are 2 options to run the tool :
-
java -jar target/JsonToJavaConverter.jar path/to/jsonfile.json outputDirectory com.your.package YourClassName
- Explanation :
- path/to/jsonfile.json: Path to your JSON file.
- outputDirectory: Directory where the Java classes will be generated.
- com.your.package: Desired package name for the generated classes.
- ClassName: Desired name for the generated class.
- Explanation :
-
java -jar target/JsonToJavaConverter.jar outputDirectory com.your.package YourClassName
- Explanation :
- outputDirectory: Directory where the Java classes will be generated.
- com.your.package: Desired package name for the generated classes.
- ClassName: Desired name for the generated class.
- After running the command, paste your JSON content into the terminal and press Ctrl+D (or Ctrl+Z on Windows) to end the input. The JSON content will be converted into Java classes.
- Explanation :
-
Because all of these would not be possible without the jsonschema2pojo dependency and the team behind that project, I want to give a special thanks to them for their excellent work in providing a valuable tool for Java developers.
3. Use jsonschema2pojo online tool for generating Java classes from JSON directly via a web interface.
Conclusion
Converting JSON to Java classes can significantly streamline your development process, especially when working with APIs and complex data structures. In this post, we explored three different ways to achieve this:
-
DIY Method: A step-by-step guide on manually converting JSON to Java classes using the jsonschema2pojo library.
-
JsonToJavaConverter Tool: An easy-to-use tool I developed to automate the process, saving you time and effort.
-
Online Tool: A convenient online tool provided by jsonschema2pojo for quick conversions without any setup.
I hope you find these methods useful for your projects. Feel free to test them out and see which one works best for you. If you encounter any issues or have suggestions for improvements, please let me know!