Converting JSON to POJOs Using Java
If you find yourself mapping JSON to POJOs but don't want to write a full class, help yourself to a handy library that does the work for you.
Join the DZone community and get the full member experience.
Join For FreeIf you have JSON that you want to map into a POJO without writing the full POJO class, then you can make use of the jsonschema2pojo library. This is an excellent library that can create Java classes using your input JSON.
Prerequisites
Program Language: Java
Pom Dependency:
<dependency>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-core</artifactId>
<version>0.4.35</version>
</dependency>
Git Repo: https://github.com/csanuragjain/extra/tree/master/convertJson2Pojo
Program
Main method:
public static void main(String[] args) {
String packageName="com.cooltrickshome";
File inputJson= new File("."+File.separator+"input.json");
File outputPojoDirectory=new File("."+File.separator+"convertedPojo");
outputPojoDirectory.mkdirs();
try {
new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Encountered issue while converting to pojo: "+e.getMessage());
e.printStackTrace();
}
}
How It Works
- packageName defines the package name of the output POJO class.
- inputJson defines the JSON that needs to be converted to POJO.
- outputPojoDirectory is the local path where POJO files would be created.
- We call the convert2JSON method that we created, passing the input JSON, output path, packageName, and the output POJO class name
convert2JSON method:
public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{
JCodeModel codeModel = new JCodeModel();
URL source = inputJson;
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
public SourceType getSourceType(){
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, className, packageName, source);
codeModel.build(outputPojoDirectory);
}
How It Works
We make an object of JCodeModel, which will be used to generate a Java class.
We define the configuration for jsonschema2pojo, which lets the program know the input source file is JSON (getSourceType method)
Now we pass the config to schemamapper, along with the codeModel created in step 1, which creates the JavaType from the provided JSON
Finally, we call the build method to create the output class.
Full Program
package com.cooltrickshome;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.jsonschema2pojo.DefaultGenerationConfig;
import org.jsonschema2pojo.GenerationConfig;
import org.jsonschema2pojo.Jackson2Annotator;
import org.jsonschema2pojo.SchemaGenerator;
import org.jsonschema2pojo.SchemaMapper;
import org.jsonschema2pojo.SchemaStore;
import org.jsonschema2pojo.SourceType;
import org.jsonschema2pojo.rules.RuleFactory;
import com.sun.codemodel.JCodeModel;
public class JsonToPojo {
/**
* @param args
*/
public static void main(String[] args) {
String packageName="com.cooltrickshome";
File inputJson= new File("."+File.separator+"input.json");
File outputPojoDirectory=new File("."+File.separator+"convertedPojo");
outputPojoDirectory.mkdirs();
try {
new JsonToPojo().convert2JSON(inputJson.toURI().toURL(), outputPojoDirectory, packageName, inputJson.getName().replace(".json", ""));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Encountered issue while converting to pojo: "+e.getMessage());
e.printStackTrace();
}
}
public void convert2JSON(URL inputJson, File outputPojoDirectory, String packageName, String className) throws IOException{
JCodeModel codeModel = new JCodeModel();
URL source = inputJson;
GenerationConfig config = new DefaultGenerationConfig() {
@Override
public boolean isGenerateBuilders() { // set config option by overriding method
return true;
}
public SourceType getSourceType(){
return SourceType.JSON;
}
};
SchemaMapper mapper = new SchemaMapper(new RuleFactory(config, new Jackson2Annotator(config), new SchemaStore()), new SchemaGenerator());
mapper.generate(codeModel, className, packageName, source);
codeModel.build(outputPojoDirectory);
}
}
Input JSON:
{
"name": "Virat",
"sport": "cricket",
"age": 25,
"id": 121,
"lastScores": [
77,
72,
23,
57,
54,
36,
74,
17
]
}
Output class generated:
package com.cooltrickshome;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name",
"sport",
"age",
"id",
"lastScores"
})
public class Input {
@JsonProperty("name")
private String name;
@JsonProperty("sport")
private String sport;
@JsonProperty("age")
private Integer age;
@JsonProperty("id")
private Integer id;
@JsonProperty("lastScores")
private List < Integer > lastScores = new ArrayList < Integer > ();
@JsonIgnore
private Map < String, Object > additionalProperties = new HashMap < String, Object > ();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
public Input withName(String name) {
this.name = name;
return this;
}
@JsonProperty("sport")
public String getSport() {
return sport;
}
@JsonProperty("sport")
public void setSport(String sport) {
this.sport = sport;
}
public Input withSport(String sport) {
this.sport = sport;
return this;
}
@JsonProperty("age")
public Integer getAge() {
return age;
}
@JsonProperty("age")
public void setAge(Integer age) {
this.age = age;
}
public Input withAge(Integer age) {
this.age = age;
return this;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
public Input withId(Integer id) {
this.id = id;
return this;
}
@JsonProperty("lastScores")
public List < Integer > getLastScores() {
return lastScores;
}
@JsonProperty("lastScores")
public void setLastScores(List < Integer > lastScores) {
this.lastScores = lastScores;
}
public Input withLastScores(List < Integer > lastScores) {
this.lastScores = lastScores;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
@JsonAnyGetter
public Map < String, Object > getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public Input withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(name).append(sport).append(age).append(id).append(lastScores).append(additionalProperties).toHashCode();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Input) == false) {
return false;
}
Input rhs = ((Input) other);
return new EqualsBuilder().append(name, rhs.name).append(sport, rhs.sport).append(age, rhs.age).append(id, rhs.id).append(lastScores, rhs.lastScores).append(additionalProperties, rhs.additionalProperties).isEquals();
}
}
Hope it helps!
Published at DZone with permission of Anurag Jain, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments