Saturday, May 27, 2017

Convert JSON to XML using Java

This post will discuss on how you can convert json to xml using Java.

Language Used:
Java

Pom Dependency:
 <!-- https://mvnrepository.com/artifact/org.json/json -->  
 <dependency>  
   <groupId>org.json</groupId>  
   <artifactId>json</artifactId>  
   <version>20170516</version>  
 </dependency>  

Git Repo:
https://github.com/csanuragjain/extra/tree/master/convertJson2XML

Program:

main method:
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  

How it works:
1) We call the method json2XML which we created passing the json to be converted
2) The return value of function contains the resulting xml

json2XML method:
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  

How it works:
1) We pass the Json String to be converted into the JSONObject
2) We use the toString method of XML class passing the json object created in Step1
3) Step2 gives the resulting xml which is then returned.
4) If you want to give a root node for resulting xml then you can provide the root xml node as second argument in toString method from Step2

Full Program:
 package com.cooltrickshome;  
 import org.json.JSONObject;  
 import org.json.XML;  
 public class Json2XML {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           // TODO Auto-generated method stub  
           String jsonString="{\"name\":\"Virat\",\"sport\":\"cricket\",\"age\":25,\"id\":121,\"lastScores\":[72,23,57,54,36,74,17]}";  
           System.out.println(new Json2XML().json2XML(jsonString));  
      }  
      public String json2XML(String jsonString){  
           JSONObject json = new JSONObject(jsonString);  
           String xml = XML.toString(json);  
           return xml;  
      }  
 }  

Input:
{"name":"Virat","sport":"cricket","age":25,"id":121,"lastScores":[77,72,23,57,54,36,74,17]}

Output:

<name>Virat</name><lastScores>77</lastScores><lastScores>72</lastScores><lastScores>23</lastScores><lastScores>57</lastScores><lastScores>54</lastScores><lastScores>36</lastScores><lastScores>74</lastScores><lastScores>17</lastScores><id>121</id><sport>cricket</sport><age>25</age>

Hope it helps :)

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 :)