Friday, May 26, 2017

Convert Json to POJO using Java

If you have a json which you want to map into POJO without writing the full POJO class then you can make use of jsonschema2pojo library. This is an excellent library which would create Java classes using your input JSON

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:
1)  packageName defines the package name of the output pojo class
2) inputJson defines the json which need to be converted to POJO
3) outputPojoDirectory is the local path where pojo files would be created
4) We call the convert2JSON method which 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:
1)  We make object of JCodeModel which will be used to generate Java class
2) We define the configuration for jsonschema2pojo which lets the program know get input source file is JSON (getSourceType method)
3)  Now we pass the config to Schemamapper along with the codeModel created in Step1 which creates the JavaType from provided Json
4) 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 :)

No comments:

Post a Comment