In this post you will learn how to Create Json from Java object
Step1: Add maven dependency.
Step2: Create a pojo model class
Step3: Create Json from Java Object
Sumit Kumar
Step1: Add maven dependency.
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version>Step2: Create a pojo model class
public class Employee{ private Integer id; private String firstName; public Employee(){} public Employee(Integer id, String name){ this.id = id; this.name = name; } public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getFirstName(){ return name; } public void setFirstName(String name){ this.name = name; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name "]"; }}Step3: Create Json from Java Object
package com.sumit.jackson;import java.io.File;import java.io.IOException;import org.codehaus.jackson.JsonGenerationException;import org.codehaus.jackson.map.JsonMappingException;import org.codehaus.jackson.map.ObjectMapper;public class JSONToJavaExample{ public static void main(String[] args){ Employee employee = new Employee(1, "Sumit Kumar"); ObjectMapper mapper = new ObjectMapper(); try{ mapper.writeValue(new File("/home/sumit/employee.json"), employee); } catch (JsonGenerationException e){ e.printStackTrace(); } catch (JsonMappingException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } }}Output://In employee.json file below content will be written{"id":1,"name":"Sumit Kumar"}
ThanksSumit Kumar
No comments:
Post a Comment