本文實例講述了Jaxb2實現JavaBean與xml互轉的方法。分享給你們供你們參考,具體以下:java
1、簡介api
JAXB(Java Architecture for XML Binding) 是一個業界的標準,是一項能夠根據XML Schema產生Java類的技術。該過程當中,JAXB也提供了將XML實例文檔反向生成Java對象樹的方法,並能將Java對象樹的內容從新寫到 XML實例文檔。數組
Jaxb 2.0是JDK 1.6的組成部分。咱們不須要下載第三方jar包 便可作到輕鬆轉換。Jaxb2使用了JDK的新特性,如:Annotation、GenericType等,須要在即將轉換的JavaBean中添加annotation註解。app
2、重要概念ide
JAXBContext類,是應用的入口,用於管理XML/Java綁定信息。工具
Marshaller接口,將Java對象序列化爲XML數據。ui
Unmarshaller接口,將XML數據反序列化爲Java對象。this
@XmlType,將Java類或枚舉類型映射到XML模式類型編碼
@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或屬性的序列化。FIELD表示JAXB將自動綁定Java類中的每一個非靜態的(static)、非瞬態的(由@XmlTransient標 注)字段到XML。其餘值還有XmlAccessType.PROPERTY和XmlAccessType.NONE。spa
@XmlAccessorOrder,控制JAXB 綁定類中屬性和字段的排序。
@XmlJavaTypeAdapter,使用定製的適配器(即擴展抽象類XmlAdapter並覆蓋marshal()和unmarshal()方法),以序列化Java類爲XML。
@XmlElementWrapper ,對於數組或集合(即包含多個元素的成員變量),生成一個包裝該數組或集合的XML元素(稱爲包裝器)。
@XmlRootElement,將Java類或枚舉類型映射到XML元素。
@XmlElement,將Java類的一個屬性映射到與屬性同名的一個XML元素。
@XmlAttribute,將Java類的一個屬性映射到與屬性同名的一個XML屬性。
3、示例
1.工具類
package cn.om.utils;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class JaxbUtil {
/**
* JavaBean裝換成xml
* 默認編碼UTF-8
* @param obj
* @return
*/
public static String converTomXml(Object obj) {
return converToXml(obj,"UTF-8");
}
/**
* JavaBean裝換成xml
* @param obj
* @param encoding
* @return
*/
private static String converToXml(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裝換成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;
}
}
須要注意的是
Marshaller.JAXB_FORMATTED_OUTPUT 決定是否在轉換成xml時同時進行格式化(即按標籤自動換行,不然便是一行的xml)
Marshaller.JAXB_ENCODING xml的編碼方式
另外,Marshaller 還有其餘Property能夠設置,能夠去查閱api。
2.轉換
package cn.com.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;
@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
*/
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCalendar() {
return calendar;
}
public void setCalendar(Date calendar) {
this.calendar = calendar;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Book [author=" + author + ", price=" + price + ", calendar=" + calendar + ", id=" + id + "]";
}
}
package cn.com.t1;
import java.util.Date;
import org.junit.Test;
import javax.xml.bind.JAXBException;
import cn.om.utils.JaxbUtil;
@SuppressWarnings("unused")
public class JaxbTest1 {
/**
* @throws JAXBException
*/
@Test
public void showMarshaller(){
Book book = new Book();
book.setId(100);
book.setAuthor("lin");
book.setCalendar(new Date());
book.setPrice(23.56f);
String str = JaxbUtil.converTomXml(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>lin</author>" +
"<calendar>2018-9-3T11:58.006</calendar>"+
"<price_1>23.56</price_1>"+
"</book>";
Book book = JaxbUtil.converyToJavaBean(str,Book.class);
System.out.println(book);
}
}
輸出結果:
三、類中包含複雜對象的轉換
3.1
package cn.com.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;
@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;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", role=" + role + "]";
}
}
3.2
package cn.com.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;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"name","desc"})
public class Role {
@XmlElement
private String name;
@XmlElement
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "Role [name="+name+",desc="+desc+"]";
}
}
3.3
package cn.com.t2;
import org.junit.Test;
import cn.om.utils.JaxbUtil;
public class JaxbTest2 {
@Test
public void showMarshaller(){
Student student = new Student();
student.setId(12);
student.setName("nihao");
Role role = new Role();
role.setDesc("管理");
role.setName("班長");
student.setRole(role);
String str = JaxbUtil.converTomXml(student);
System.out.println(str);
}
@Test
public void showUnMarshaller(){
String str = "<?xml version =\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"+
"<student id =\"12\">"+
"<name>nihao</name>" +
"<role>"+
"<desc>管理</desc>"+
"<name>班長</name>"+
"</role>"+
"</student>";
Student student = JaxbUtil.converyToJavaBean(str, Student.class);
System.out.println(student);
}
}
輸出結果
四、集合對象的轉換(一樣適用於Set)
4.1
package cn.com.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;
@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;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Province> getProvinceList() {
return provinceList;
}
public void setProvinceList(List<Province> provinceList) {
this.provinceList = provinceList;
}
@Override
public String toString(){
return "Country [name = "+ name +",provinceList" + provinceList + "]";
}
}
4.2
package cn.com.t3;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"name","provCity"})
public class Province {
@XmlElement(name = "province_name")
private String name;
@XmlElement(name = "prov_city")
private String provCity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvCity() {
return provCity;
}
public void setProvCity(String provCity) {
this.provCity = provCity;
}
@Override
public String toString(){
return "Province [name=" + name +", provCity=" + provCity + "]";
}
}
4.3
package cn.com.t3;
import java.util.List;
import java.util.ArrayList;
import org.junit.Test;
import cn.om.utils.JaxbUtil;
public class JaxbTest3 {
@Test
public void showShaller(){
Country country = new Country();
country.setName("中國");
List<Province> list = new ArrayList<Province>();
Province province = new Province();
province.setName("遼寧省");
province.setProvCity("大連市");
Province province2 = new Province();
province2.setName("黑龍江省");
province2.setProvCity("哈爾濱市");
list.add(province);
list.add(province2);
country.setProvinceList(list);
String str = JaxbUtil.converTomXml(country);
System.out.println(str);
}
@Test
public void showUnShaller(){
String str = "<?xml version =\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"+
"<country>"+
"<country_name>中國</country_name>"+
"<provinces>"+
"<province>"+
"<province_name>遼寧省</province_name>"+
"<prov_city>大連市</prov_city>"+
"</province>"+
"<province>"+
"<province_name>黑龍江省</province_name>"+
"<prov_city>哈爾濱市</prov_city>"+
"</province>"+
"</provinces>"+
"</country>";
Country country = JaxbUtil.converyToJavaBean(str, Country.class);
System.out.println(country);
}
}
輸出結果:
其中運行後錯誤:
紅框處province少寫一個n,獲取不到省份信息
紅框處prov_city沒有和前面的匹配上,因此獲取不到任何的值
儘可能手敲這個代碼,不要複製!!!
參考文章:
https://blog.csdn.net/u010502101/article/details/79586834