A detailed explanation of the method of Jaxb2 to realize the reciprocal of JavaBean and xml

  • 2020-06-19 10:21:54
  • OfStack

An example of Jaxb2 is presented in this paper. To share for your reference, specific as follows:

1. Introduction

JAXB (Java Architecture for XML Binding) is an industry standard and a technology that generates Java classes based on XML Schema. In this process, JAXB also provides a way to reverse-generate the Java object tree from the XML instance document and re-write the contents of the Java object tree to the XML instance document.

Jaxb 2.0 is part of JDK 1.6. We don't need to download the third side jar package to make the conversion easy. Jaxb2 USES new features of JDK, such as Annotation, GenericType, etc. annotation annotations will be added to the JavaBean to be converted.

2. Important concepts

The JAXBContext class is the entry point to the application to manage the XML/Java binding information.

Marshaller interface, which serializes Java objects to XML data.

Unmarshaller interface, which deserializes XML data into Java objects.

XmlType, maps the Java class or enumeration type to the XML schema type

XmlAccessorType(XmlAccessType.FIELD), which controls the serialization of fields or properties. FIELD means that JAXB will automatically bind every non-static (static), non-transient (annotated by @XmlTransient) field in the Java class to XML. Other values are ES66en.PROPERTY and XmlAccessType.NONE.

XmlAccessorOrder, which controls the sort of properties and fields in the JAXB binding class.

XmlJavaTypeAdapter to serialize the Java class to XML using a custom adapter that extends the abstract class XmlAdapter and overrides the marshal() and unmarshal() methods.

For an array or collection (that is, a member variable containing multiple elements), generate 1 XML element (called a wrapper) that wraps the array or collection.

@ES88en maps the Java class or enumeration type to the XML element.

XmlElement, maps an attribute of the Java class to an XML element with the same name as the attribute.

@XmlAttribute, map 1 property of the Java class to 1 XML property of the same name as the property.

Example 3.

1. Preparation


package utils;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
 * Jaxb2 Utility class 
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:40:14
 */
public class JaxbUtil {
  /**
   * JavaBean Converted to xml
   *  The default encoding UTF-8
   * @param obj
   * @param writer
   * @return
   */
  public static String convertToXml(Object obj) {
    return convertToXml(obj, "UTF-8");
  }
  /**
   * JavaBean Converted to xml
   * @param obj
   * @param encoding
   * @return
   */
  public static String convertToXml(Object obj, String encoding) {
    String result = null;
    try {
      JAXBContext context = JAXBContext.newInstance(obj.getClass());
      Marshaller marshaller = context.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
      StringWriter writer = new StringWriter();
      marshaller.marshal(obj, writer);
      result = writer.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  /**
   * xml Converted to JavaBean
   * @param xml
   * @param c
   * @return
   */
  @SuppressWarnings("unchecked")
  public static <T> T converyToJavaBean(String xml, Class<T> c) {
    T t = null;
    try {
      JAXBContext context = JAXBContext.newInstance(c);
      Unmarshaller unmarshaller = context.createUnmarshaller();
      t = (T) unmarshaller.unmarshal(new StringReader(xml));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return t;
  }
}

It's pretty straightforward, but it's important to note


marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

Marshaller.JAXB_FORMATTED_OUTPUT determines whether to format the conversion to xml at the same time (that is, wrap the line automatically according to the label, otherwise it is xml for 1 line)

Marshaller.JAXB_ENCODING xml

In addition, Marshaller has other Property Settings. You can check out api.

2. Simplest conversion


package t1;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:49:48
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(name = "book", propOrder = { "author", "calendar", "price", "id" })
public class Book {
  @XmlElement(required = true)
  private String author;
  @XmlElement(name = "price_1", required = true)
  private float price;
  @XmlElement
  private Date calendar;
  @XmlAttribute
  private Integer id;
  /**
   * @return the author
   */
  public String getAuthor() {
    return author;
  }
  /**
   * @return the price
   */
  public float getPrice() {
    return price;
  }
  /**
   * @return the calendar
   */
  public Date getCalendar() {
    return calendar;
  }
  /**
   * @return the id
   */
  public Integer getId() {
    return id;
  }
  /**
   * @param author the author to set
   */
  public void setAuthor(String author) {
    this.author = author;
  }
  /**
   * @param price the price to set
   */
  public void setPrice(float price) {
    this.price = price;
  }
  /**
   * @param calendar the calendar to set
   */
  public void setCalendar(Date calendar) {
    this.calendar = calendar;
  }
  /**
   * @param id the id to set
   */
  public void setId(Integer id) {
    this.id = id;
  }
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Book [author=" + author + ", price=" + price + ", calendar=" + calendar + ", id=" + id + "]";
  }
}


package t1;
import java.util.Date;
import javax.xml.bind.JAXBException;
import org.junit.Test;
import utils.JaxbUtil;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:50:00
 */
public class JaxbTest1 {
  /**
   * @throws JAXBException
   */
  @Test
  public void showMarshaller() {
    Book book = new Book();
    book.setId(100);
    book.setAuthor("James");
    book.setCalendar(new Date());
    book.setPrice(23.45f);  // The default is 0.0
    String str = JaxbUtil.convertToXml(book);
    System.out.println(str);
  }
  /**
   * @throws JAXBException
   */
  @Test
  public void showUnMarshaller() {
    String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
      "<book id=\"100\">" +
      "  <author>James</author>" +
       "  <calendar>2013-03-29T09:25:56.004+08:00</calendar>" +
       " <price_1>23.45</price_1>" +
      "</book>";
    Book book = JaxbUtil.converyToJavaBean(str, Book.class);
    System.out.println(book);
  }
}

The output results are as follows:


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="100">
  <author>James</author>
  <calendar>2013-03-29T14:50:58.974+08:00</calendar>
  <price_1>23.45</price_1>
</book>
Book [author=James, price=23.45, calendar=Fri Mar 29 09:25:56 CST 2013, id=100]

3, class contains complex object transformation


package t2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:51:44
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "student")
@XmlType(propOrder = {})
public class Student {
  @XmlAttribute
  private Integer id;
  @XmlElement
  private String name;
  @XmlElement(name = "role")
  private Role role;
  /**
   * @return the id
   */
  public Integer getId() {
    return id;
  }
  /**
   * @return the name
   */
  public String getName() {
    return name;
  }
  /**
   * @return the role
   */
  public Role getRole() {
    return role;
  }
  /**
   * @param id the id to set
   */
  public void setId(Integer id) {
    this.id = id;
  }
  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }
  /**
   * @param role the role to set
   */
  public void setRole(Role role) {
    this.role = role;
  }
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Student [id=" + id + ", name=" + name + ", role=" + role + "]";
  }
}


package t2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:51:52
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "desc" })
public class Role {
  @XmlElement
  private String name;
  @XmlElement
  private String desc;
  /**
   * @return the name
   */
  public String getName() {
    return name;
  }
  /**
   * @return the desc
   */
  public String getDesc() {
    return desc;
  }
  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }
  /**
   * @param desc the desc to set
   */
  public void setDesc(String desc) {
    this.desc = desc;
  }
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Role [name=" + name + ", desc=" + desc + "]";
  }
}


package t2;
import org.junit.Test;
import utils.JaxbUtil;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:52:00
 */
public class JaxbTest2 {
  @Test
  public void showMarshaller() {
    Student student = new Student();
    student.setId(12);
    student.setName("test");
    Role role = new Role();
    role.setDesc(" management ");
    role.setName(" Monitor of the class ");
    student.setRole(role);
    String str = JaxbUtil.convertToXml(student);
    System.out.println(str);
  }
  @Test
  public void showUnMarshaller() {
    String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"+
      "<student id=\"12\">"+
      "  <name>test</name>"+
       "  <role>"+
       "   <name> Monitor of the class </name>"+
        "   <desc> management </desc>"+
        "</role>"+
      "</student>";
    Student student = JaxbUtil.converyToJavaBean(str, Student.class);
    System.out.println(student);
  }
}

The output results are as follows:


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="12">
  <name>test</name>
  <role>
    <name> Monitor of the class </name>
    <desc> management </desc>
  </role>
</student>
Student [id=12, name=test, role=Role [name= Monitor of the class , desc= management ]]

4. Transformation of collection objects (also for Set)


package t3;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
 * @author   zhuc
 * @create   2013-3-29  In the afternoon 2:55:56
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "country")
@XmlType(propOrder = { "name", "provinceList" })
public class Country {
  @XmlElement(name = "country_name")
  private String name;
  @XmlElementWrapper(name = "provinces")
  @XmlElement(name = "province")
  private List<Province> provinceList;
  /**
   * @return the name
   */
  public String getName() {
    return name;
  }
  /**
   * @return the provinceList
   */
  public List<Province> getProvinceList() {
    return provinceList;
  }
  /**
   * @param name the name to set
   */
  public void setName(String name) {
    this.name = name;
  }
  /**
   * @param provinceList the provinceList to set
   */
  public void setProvinceList(List<Province> provinceList) {
    this.provinceList = provinceList;
  }
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return "Country [name=" + name + ", provinceList=" + provinceList + "]";
  }
}


marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

0

marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

1

The output results are as follows:


marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

2

PS: Here is another JavaBean online tool for your reference:

Online JSON to Java Bean code tool:
http://tools.ofstack.com/code/json2javabean

I hope this article has been helpful in java programming.


Related articles: