Pages

Wednesday, October 26, 2011

Using JAXB


One recurrent topic in my projects is the serialization of Java beans in XML and vice versa. Currently, I am using Java Architecture for XML Binding (JAXB), so I decided to write a small example based on Maven to illustrate the use of the framework.

In order to use JAXB, I followed several steps:

- Create XML schema files under /src/main/xsd. In this example, I created the "Person.xsd".


 
  
   
   
  
 


- Generate sources (bean) from previous xsd files:
mvn clean jaxb2:xjc

These two steps are optional if you create and annotate consequently your own java classes.

- Create utility methods to marshall Java objects object in xml
public static void serialize(Object o, Writer writer) throws JAXBException {
  // write it out as XML
  final JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());

  // for cool output
  Marshaller marshaller = jaxbContext.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.marshal(o, writer);
 }

- Create utility methods unmarshall an xml document to obtain Java objects
public static  O deserialize(Class clazz, Reader reader)
   throws JAXBException {

  final JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
  final O object = (O) jaxbContext.createUnmarshaller().unmarshal(reader);
  return object;
 }

- Manipulate Java beans and XML documents
@Test
 public void testSerializeGeneric() throws IOException, JAXBException {
  Person person = new ObjectFactory().createPerson();
  person.setId(1);
  person.setName("John Doe");

  StringWriter expected = new StringWriter();
  Serializer.serialize(person, expected);

  Person p = Serializer.deserialize(Person.class, new StringReader(
    expected.toString()));
  StringWriter actual = new StringWriter();
  Serializer.serialize(p, actual);

  // Assert.assertEquals(person.getId(), p.getId());
  Assert.assertEquals(expected.toString(), actual.toString());
 }

Here is the pom that I used in this example.

 4.0.0
 
  MySuperPom
  org.example
  1.0
 
 org.examples.jaxb
 jaxb-example
 0.0.1-SNAPSHOT
 JAXB Example

 
  
   javax.xml.bind
   jaxb-api
   2.2
  

  
   com.sun.xml.bind
   jaxb-impl
   2.2.4
  

  
   junit
   junit
   4.8.1
   test
  

 

 
  
   
    org.codehaus.mojo
    jaxb2-maven-plugin
    1.3.1

    
     org.jaxb.example.model
    
   

   
    org.apache.maven.plugins
    maven-compiler-plugin
    2.3.1
    
     
     1.6
     1.6
     UTF-8
    
   
   
    org.apache.maven.plugins
    maven-jar-plugin
    2.3.1
    
     
     1.6
     1.6
     UTF-8
    
   

  
 


No comments:

Post a Comment

/* */