Generate classes from json java

Generate classes from json java

In some cases, we need to use JSON files to create Java classes, also known as POJOs. This is possible without having to use the convenient ** jsonschema2pojo ** library to write the entire class from scratch.

In this tutorial, we will see how to use this library to create Java classes from JSON objects.

2.Settings

The jsonschema2pojo-core dependency converts JSON objects into Java classes:

 
org.jsonschema2pojo
jsonschema2pojo-core
1.1.1

3.JSON to Java class conversion

Let’s see how to jsonschema2pojo write a program using a library that converts JSON files into Java classes.

First, we will create a method to convertJsonToJavaClass convert a JSON file into a POJO class and accept four parameters:

  • A inputJson file URL
  • Will generate POJO outputJavaClassDirectory
  • The POJO class belongs to packageName
  • Output POJO className .
Читайте также:  Ссылка вернуться назад html

Then, we will define the steps in this method:

  • We will start by creating the JCodeModel object of the class, which will generate the Java class
  • Then, we will define jsonschema2pojo the configuration, which allows the program to recognize that the input source file is JSON ( getSourceType method)
  • In addition, we pass this configuration to RuleFactory and it will be used to create type generation rules for this mapping
  • We will use this factory and SchemaGenerator SchemaMapper it will generate Java types from the provided JSON
  • Finally, we will call the JCodeModel build method to create the output class

Let’s see the implementation:

public void convertJsonToJavaClass(URL inputJsonUrl, File outputJavaClassDirectory, String packageName, String javaClassName) 
throws IOException JCodeModel jcodeModel = new JCodeModel();
GenerationConfig config = new DefaultGenerationConfig() < @Override
public boolean isGenerateBuilders() < return true;
>
@Override
public SourceType getSourceType() < return SourceType.JSON;
>
>;
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(jcodeModel, javaClassName, packageName, inputJsonUrl);
jcodeModel.build(outputJavaClassDirectory);
>

4.Input and Output

Let’s use this sample JSON to execute the program:

After executing the program, it creates the following Java classes in the given directory:

@JsonInclude(JsonInclude.Include.NON_NULL) 
@JsonPropertyOrder()
@Generated("jsonschema2pojo")
public class Input @JsonProperty("name")
private String name; @JsonProperty("area")
private String area; @JsonProperty("author")
private String author; @JsonProperty("id")
private Integer id; @JsonProperty("topics")
private List topics = new ArrayList(); @JsonProperty("address")
private Address address; @JsonIgnore
private Map additionalProperties = new HashMap();
// getters & setters
// hashCode & equals
// toString
>

**Please note that it is therefore also a nested JSON object Address ** class:

@JsonInclude(JsonInclude.Include.NON_NULL) 
@JsonPropertyOrder()
@Generated("jsonschema2pojo")
public class Address @JsonProperty("city")
private String city; @JsonProperty("country")
private String country; @JsonIgnore
private Map additionalProperties = new HashMap();
// getters & setters
// hashCode & equals
// toString
>

We can also achieve all of this by simply visiting jsonschema2pojo.org . jsonschema2pojo The tool uses JSON (or YAML) mode documents and generates DTO-style Java classes. It provides many options that you can choose to include in a Java class, including constructors hashCode, equals, and toString methods.

Источник

Convert JSON to POJO Objects in Java Online

Convert any JSON object to a POJO JAVA class online. Check below panel on how to use this converter and how to deserialize using Jackson librairy.

JSON to C# Converter

XML to C# Converter

C# Classes to Object Initializers

JSON to JAVA Converter

XML to POJO Converter

JSON to Python Converter

JSON to Dart Converter

SCSS to CSS Converter

LESS to CSS Converter

Case Converter

Remove Duplicate Lines Online

Inner Join on Two Lists

Exlusive Left Join on Two Lists

Exlusive Right Join on Two Lists

Exlusive Full Join on Two Lists

Inclusive Full Join on Two Lists

Oops! Houston we have a problem.

Looks like there’s an unhandled error or your input is not properly formatted. You can report it to the developer by clicking on the «Report To Dev» button. Or you can report it on Github using «Report An Issue».

Exception:

How do you convert a JSON string to POJO objects and deserialize using Jackson ?

 JSON to JAVA POJO converter

Here’s how you can convert your JSON string to JAVA objects, we will be using the converter and external libraries like Jackson objectmapper to parse our object.

You can find the source code for this example: HERE

1. Copy and paste your JSON in the first code editor and click «Convert»

Make sure that your JSON object is not large (over 5MB) and is formatted. You can use any JSON format validator online.

You can choose from the settings to format the POJOs into properties (get, set methods) or keep it as fields. This step will not affect our deserialization process.

Let’s set an example JSON and work with it during the steps:

< "Test":< "id":4, "userid":"user_id_value", "object": , "created_at":"2012-06-02 23:33:90", "updated_at":"2013-06-02 23:33:90", "users":[ < "id":"2", "name":"Test" >, < "id":"6", "name":"Test Child 1" >] >, "Test2" : < "Prop2" : "SomeVal2" >>

2. Click on «Copy to Clipboard» when the JAVA object classes appear in the second window

This will copy the classes to the clipboard. Here are the classes returned:

public class Object < public int prop1; public String prop2; >public class User < public String id; public String name; >public class Test < public int id; public String userid; public Object object; public String created_at; public String updated_at; public List users; >public class Test2 < @JsonProperty("Prop2") public String prop2; >public class Root

You’ll notice that there’s a » JsonProperty » attribute on some fields that contains the original property name as in the JSON object. This is to tell our fellow Jackson that this field in the java class is named differently than in the JSON object.

Note that we will be using the «Root» class to deserialize our JSON child elements. This will take into consideration that you might have two root notes in your JSON object.

3. Import Jackson libraries

Assuming that you have your favorite IDE opened, your next step is to import the Jackson packages and create the classes returned from the tool.

You will need three Jackson packages:

The «jackson-annotations-2.11.1» is used to add the «JsonProperty» attributes. The «jackson-databind-2.11.1» is used to create the ObjectMapper class which will help us in reading the JSON and map it to our Root Object.

Here’s a LINK to the Jackson maven repositories. You can import them manually or using maven whichever you prefer. Note that we will not cover how to import packages into your source code in this article.

4. Create POJO classes to map your JSON string

We then create our classes and add any imports needed:

 jackson-java-classes

5. Create ObjectMapper class and deserialize into a Root class

Here, we’re just creating an ObjectMapper class and calling the «readValue» method. Notice that i’m reading the JSON string from a file system, in your case you might be returning a JSON string from an API or a client.

We then supply the class object of our «Root» class by doing «Root.class».

 jackson-objectmapper

When debugging, you’ll notice that our objects have been filled accordingly:

 Java Debugging

You can find the source code for this example: HERE

Code Converters

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Generate Java classes (POJOs) from JSON

Sharelison/JsonToJava

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Library to generate Java POJO from JSON files or JSON string.

Add library as a dependency to your project to get started.

Download the following JAR and add it to your classpath:

Add dependency io.github.sharelison:jsontojava in your POM.

  io.github.sharelison jsontojava 1.0.1   
String complexJson = "\"prop1\": \"value\">"; JsonToJava jsonToJava = new JsonToJava(); //jackson annotations is generated by default. use jsonToJava.jsonToJava(complexJson, "MyJsonToJavaObject", "org.example.jsontojava", "jsontojava/output", false) to generate class without annotations. jsonToJava.jsonToJava(complexJson, "MyJsonToJavaObject", "org.example.jsontojava", "jsontojava/output"); // MyJsonToJavaObject.java will be generated in jsontojava/output.

Only .json and .txt files supported as json input file.

String pathToJsonFile = "input/MyJsonToJavaObject.json"; JsonToJava jsonToJava = new JsonToJava(); //jackson annotations is generated by default. use jsonToJava.jsonToJava(pathToJsonFile, "MyJsonToJavaObject", "org.example.jsontojava", false) to generate class without annotations. ListJsonClassResult> jsonResult = jsonToJava.jsonToJava(pathToJsonFile, "MyJsonToJavaObject", "org.example.jsontojava"); //Do something with generated list of classes created. //Class JsonClassResult holds 2 String properties: The object name and the generated class in a string.

Источник

Оцените статью