In this post you will learn how to get a Java object from a given XML.
Step1: Add maven dependency.
Step2: Create a pojo model class
@XmlRootElement
Step3: Create Java Object from Json
File file=new File("/home/sumit/Desktop/sample.xml");
JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
Employee employee=(Employee)jaxbUnmarshaller.unmarshal(file);
System.out.println(employee);
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
package com.sumit.xmlJava;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement
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; } @XmlElement public void setId(Integer id){ this.id = id; } public String getFirstName(){ return name; } @XmlElement public void setFirstName(String name){ this.name = name; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name "]"; }}Step3: Create Java Object from Json
package com.sumit.xmlJava;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){ try {File file=new File("/home/sumit/Desktop/sample.xml");
JAXBContext jaxbContext=JAXBContext.newInstance(Employee.class);
Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
Employee employee=(Employee)jaxbUnmarshaller.unmarshal(file);
System.out.println(employee);
}}
Output: Employee [id=1, name=Sumit Kumar]Note: File /home/sumit/Desktop/sample.xml Contains following data
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<employee>
<id>1</id>
<name>Sumit Kumar</name>
</employee>
<employee>
<id>1</id>
<name>Sumit Kumar</name>
</employee>
ThanksSumit Kumar
No comments:
Post a Comment