Created
March 4, 2011 05:45
-
-
Save mohamedmansour/854233 to your computer and use it in GitHub Desktop.
JAXB Example for Stackoverflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.StringReader; | |
import java.io.StringWriter; | |
import javax.xml.bind.JAXBContext; | |
import javax.xml.bind.JAXBException; | |
import javax.xml.bind.Marshaller; | |
import javax.xml.bind.Unmarshaller; | |
import javax.xml.bind.annotation.XmlAccessType; | |
import javax.xml.bind.annotation.XmlAccessorType; | |
import javax.xml.bind.annotation.XmlElement; | |
import javax.xml.bind.annotation.XmlRootElement; | |
/** | |
* JAXB Example for Stackoverflow | |
* http://stackoverflow.com/questions/5189690/how-to-serialize-and-de-serialize-objects-using-jaxb/5189960#5189960 | |
* | |
* @author Mohamed Mansour | |
* @since 2011-03-04 | |
*/ | |
public class JAXB { | |
public static void main(String[] args) throws JAXBException { | |
Student student = new Student(); | |
student.setAge(25); | |
student.setName("Some Kid"); | |
System.out.println(serialize(student)); | |
} | |
/** | |
* Serialize a Student to an XML String. | |
* @param student The student to serialize. | |
* @return XML String. | |
* @throws JAXBException | |
*/ | |
public static final String serialize(Student student) throws JAXBException { | |
StringWriter writer = new StringWriter(); | |
JAXBContext context = JAXBContext.newInstance(Student.class); | |
Marshaller m = context.createMarshaller(); | |
m.marshal(student, writer); | |
return writer.toString(); | |
} | |
/** | |
* Deserialize an XML String that represents a Student object. | |
* @param input The XML String to deserialize. | |
* @return A Student object. | |
* @throws JAXBException | |
*/ | |
public static final Student deserialize(String input) throws JAXBException { | |
JAXBContext context = JAXBContext.newInstance(Student.class); | |
Unmarshaller m = context.createUnmarshaller(); | |
return (Student)m.unmarshal(new StringReader(input)); | |
} | |
@XmlRootElement(name="student") | |
@XmlAccessorType(XmlAccessType.NONE) | |
static class Student { | |
@XmlElement(name="name") | |
private String name; | |
@XmlElement(name="age") | |
private int age; | |
public Student() { | |
} | |
public void setName(String name) { this.name = name; } | |
public String getName() { return name; } | |
public void setAge(int age) { this.age = age; } | |
public int getAge() { return age; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment