Adams Bros Blog

7Feb/1042

What is JAXB and JAXB Example Code

I thought it may be nice for those googlers that want to know about JAXB, to have a quick working example to use.  So, that is the purpose of this post.

First off, what is JAXB?  Well, simply put, JAXB is for converting Java objects to XML or from XML to Java objects.  With the advent of Java 1.5, and annotations, this becomes extremely simple.

Download JAXB, dependencies to your local computer, and put them in a folder called "libs". The dependencies JARs I have are...

  • activation-1.1.jar
  • jaxb-api-2.0.jar
  • jaxb-impl-2.0.5.jar
  • jsr173_api-1.0.jar

Copy the following Java source code to Employee.java, and proceed with the instructions below

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.*;
import java.io.StringReader;
import java.io.StringWriter;
 
@XmlRootElement(name = "employee")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employee
{
    public static void main(String args[]) throws JAXBException
    {
        final Employee john = new Employee();
        john.setId(1);
        john.setFirstName("John");
        john.setMiddleName("Robert");
        john.setLastName("Doe");
 
        // write it out as XML
        final JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
        StringWriter writer = new StringWriter();
        jaxbContext.createMarshaller().marshal(john, writer);
 
        // read it from XML
        final Employee johnRead =
            (Employee) jaxbContext.createUnmarshaller().unmarshal(
                new StringReader(writer.toString()));
        if (john.equals(johnRead))
        {   // write the new object out as XML again.
            writer = new StringWriter();
            jaxbContext.createMarshaller().marshal(johnRead, writer);
            System.out.println(
                "johnRead was identical to john: \n" + writer.toString());
        }
        else
        {
            System.out.println("john and johnRead are not equal");
        }
    }
 
    @XmlAttribute
    private int id;
 
    /**
     * Employee's first name
     */
    @XmlElement
    private
    String firstName;
 
    /**
     * Employee's middle name
     */
    @XmlElement
    private
    String middleName;
 
    /**
     * Employee's last name
     */
    @XmlElement
    private
    String lastName;
 
    public Employee()
    {
    }
 
    public int getId()
    {
        return id;
    }
 
    public void setId(int id)
    {
        this.id = id;
    }
 
    public String getLastName()
    {
        return lastName;
    }
 
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
 
    public String getMiddleName()
    {
        return middleName;
    }
 
    public void setMiddleName(String middleName)
    {
        this.middleName = middleName;
    }
 
    public String getFirstName()
    {
        return firstName;
    }
 
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
 
    @Override
    public boolean equals(Object o)
    {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        Employee employee = (Employee) o;
 
        if (id != employee.id) return false;
        if (firstName != null ? !firstName.equals(employee.firstName) :
            employee.firstName != null) return false;
        if (lastName != null ? !lastName.equals(employee.lastName) :
            employee.lastName != null) return false;
        if (middleName != null ? !middleName.equals(employee.middleName) :
            employee.middleName != null) return false;
 
        return true;
    }
 
    @Override
    public int hashCode()
    {
        int result = id;
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (middleName != null ? middleName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        return result;
    }
 
    @Override
    public String toString()
    {
        return "Employee{" +
            "id=" + id +
            ", firstName='" + firstName + '\'' +
            ", middleName='" + middleName + '\'' +
            ", lastName='" + lastName + '\'' +
            '}';
    }
}

The following commands will compile and run the source, if under a unix OS. If in windows, you'll need to form your own classpath.

javac -classpath .:$(for jar in libs/*.jar; do echo -n "$jar:"; done) Employee.java
java -classpath .:$(for jar in libs/*.jar; do echo -n "$jar:"; done) Employee

The output should be as follows, but the XML will be on a single line...

johnRead was identical to john:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="1">
 <firstName>John</firstName>
 <middleName>Robert</middleName>
 <lastName>Doe</lastName>
</employee>
Comments (42) Trackbacks (0)
  1. Excellent working example thanks a lot.

  2. Nice work !!

  3. Great example. Thanks.

    Just a note: to make the marshaller output pretty printed XML, just add:

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  4. Thank you it helps me lot

  5. thanks, I hope to see more examples to cover most of features in JAXB,
    Thanks again

  6. thank you. 🙂 i know thanking matters.

  7. thanks the example really helped

  8. Thanks!!! Nice example, thank you again 😀

  9. Thank you. It helps me Alot.

  10. Thanks….great example; worked for me as well.

  11. Thank you for making an example that didn’t include all the stuff with schema generation, class generation or the jaxb object factorys. My head was starting to hurt looking at all that stuff!!

  12. However for the beginners, this example is very useful. Thanks you for this example.
    It helped me to understand what is JAXB…

    Thanks…

  13. Thanks dude, gr8 Job

  14. Thanks a lot

  15. This should be shown as a web service example. Java and XML is used as web service.

  16. Hi Roben,

    JAXB is not a web service. It can be used in REST based web services, it is not a web service itself.

    But yes, that would be a good thing to blog about, if it’s not already easily found on google.

  17. Thanks for your short and sweet Example

  18. great help, thanks lot !!!

  19. Sigh. What a clean example! Good job, bro!

  20. Great and simple example for beginners…

  21. A good quick example to start with JAXB.
    Thanks a ton !!!!

  22. Excellent work… 🙂

  23. works fine for me also ,thanx

  24. Excellent Example

  25. Thanks for the providing the simple example; very useful especially to newbies to Jaxb.

  26. Good Example

  27. Is there a way how, using this example, to create output document without “standalone=”yes””?

  28. pretty printed XML output:
    if (john.equals(johnRead))
    { // write the new object out as XML again.
    writer = new StringWriter();
    Marshaller marshaller =jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(johnRead, writer);

    System.out.println(“johnRead was identical to john: \n” + writer.toString());
    }
    else
    {
    System.out.println(“john and johnRead are not equal”);
    }

  29. Really simplest and coolest example

  30. how to convert xml to java object..

    i would appreciate that example.

  31. Nice example,easy to understand!

  32. It’s not working on jdk1.5.
    Do you have any solution for that.


Leave a comment

 

No trackbacks yet.