Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize and de-serialize objects using JAXB?

Tags:

java

jaxb

I have an issue. I want to convert an object into another object using JAXB. As in, I have a class com.home.Student, and another class com.school.Student, both have same arguments, in fact both are same (copy paste), but different package. I want to perform the conversion between them using JAXB.

How to do that, please help me.

like image 860
M.J. Avatar asked Mar 04 '11 04:03

M.J.


People also ask

What is Serialization & de serialization give an example?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.

Which annotation is needed for serialization and deserialization of XML format?

Jackson annotations are useful in defining and controlling the process of serialization and deserialization across various formats such as XML, JSON, and YAML. Some annotations work for all formats and some are tied to a specific type of file.

What is XML serialization in Java?

Serialization of Java Objects to XML can be done using XMLEncoder, XMLDecoder. Java Object Serialization feature was introduced in JDK 1.1. Serialization transforms a Java object or graph of Java object into an array of bytes which can be stored in a file or transmitted over a network.


2 Answers

It would be nice if you included some code that explains your problem.

JAXB 101 says you should place the right annotations, then you can serialize and deserialize correctly. You should properly annotate your classes with @XmlRootElement, @XmlElement, @XmlAttribute, etc

For example:

@XmlRootElement(name="student") @XmlAccessorType(XmlAccessType.NONE) class Student {   @XmlElement(name="name")   private String name;    @XmlElement(name="age")   private int age;    public Student() {   }    public String getName() { return name; }    public int getAge() { return age; } } 

Then you can use serialize it using JAXB Marshaller:

StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(Student.class); Marshaller m = context.createMarshaller(); m.marshal(student, writer); 

And deserialize it as well by Unmarshelling the input ..

JAXBContext context = JAXBContext.newInstance(Student.class); Unmarshaller m = context.createUnmarshaller(); return (Student)m.unmarshal(new StringReader(input)); 

Make sure you look at the JavaDoc I mentioned above since there are many ways to do so.

If you cannot modify your classes, you can still use JAXB (or you can use XStream) Assuming your class is the following:

class Student {   private String name;   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; } } 

You can serialize it by doing:

Student student = new Student(); student.setAge(25); student.setName('FooBar'); StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(Student.class); Marshaller m = context.createMarshaller(); m.marshal(new JAXBElement(new QName(Student.class.getSimpleName()), Student.class, student), writer); System.out.println(writer.toString()); 

If you are using XStream, you can do the serialization without Annotations too (and it is more controllable). http://x-stream.github.io/tutorial.html

like image 113
Mohamed Mansour Avatar answered Oct 06 '22 00:10

Mohamed Mansour


You could do the following.

Note:

  • It does not require that you ever materialize the data as XML, by leveraging JAXBSource.
  • It does not require any annotations on your object model.

com.home.Student

package com.home;  public class Student {      private String name;     private Status status;      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public Status getStatus() {         return status;     }      public void setStatus(Status status) {         this.status = status;     }  } 

com.home.Status

package com.home;  public enum Status {      FULL_TIME("F"),     PART_TIME("P");      private final String code;      Status(String code) {         this.code = code;     }      public String getCode() {         return code;     }  } 

com.school.Student

package com.school;  public class Student {      private String name;     private Status status;      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public Status getStatus() {         return status;     }      public void setStatus(Status status) {         this.status = status;     }  } 

com.school.Status

package com.school;  public enum Status {      FULL_TIME("F"),     PART_TIME("P");      private final String code;      Status(String code) {         this.code = code;     }      public String getCode() {         return code;     }  } 

com.example.Demo;

package com.example;  import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Unmarshaller; import javax.xml.bind.util.JAXBSource; import javax.xml.namespace.QName;  public class Demo {      public static void main(String[] args) throws Exception {         com.home.Student studentA = new com.home.Student();         studentA.setName("Jane Doe");         studentA.setStatus(com.home.Status.FULL_TIME);          JAXBContext contextA = JAXBContext.newInstance(com.home.Student.class);         JAXBElement<com.home.Student> jaxbElementA = new JAXBElement(new QName("student"), com.home.Student.class, studentA);         JAXBSource sourceA = new JAXBSource(contextA, jaxbElementA);          JAXBContext contextB = JAXBContext.newInstance(com.school.Student.class);         Unmarshaller unmarshallerB = contextB.createUnmarshaller();         JAXBElement<com.school.Student> jaxbElementB = unmarshallerB.unmarshal(sourceA, com.school.Student.class);          com.school.Student studentB = jaxbElementB.getValue();         System.out.println(studentB.getName());         System.out.println(studentB.getStatus().getCode());     }  } 
like image 23
bdoughan Avatar answered Oct 05 '22 23:10

bdoughan