Jaxb2實(shí)現(xiàn)JavaBean與xml互轉(zhuǎn)的方法詳解
本文實(shí)例講述了Jaxb2實(shí)現(xiàn)JavaBean與xml互轉(zhuǎn)的方法。分享給大家供大家參考,具體如下:
一、簡(jiǎn)介
JAXB(Java Architecture for XML Binding) 是一個(gè)業(yè)界的標(biāo)準(zhǔn),是一項(xiàng)可以根據(jù)XML Schema產(chǎn)生Java類的技術(shù)。該過程中,JAXB也提供了將XML實(shí)例文檔反向生成Java對(duì)象樹的方法,并能將Java對(duì)象樹的內(nèi)容重新寫到 XML實(shí)例文檔。
Jaxb 2.0是JDK 1.6的組成部分。我們不需要下載第三方j(luò)ar包 即可做到輕松轉(zhuǎn)換。Jaxb2使用了JDK的新特性,如:Annotation、GenericType等,需要在即將轉(zhuǎn)換的JavaBean中添加annotation注解。
二、重要概念
JAXBContext類,是應(yīng)用的入口,用于管理XML/Java綁定信息。
Marshaller接口,將Java對(duì)象序列化為XML數(shù)據(jù)。
Unmarshaller接口,將XML數(shù)據(jù)反序列化為Java對(duì)象。
@XmlType,將Java類或枚舉類型映射到XML模式類型
@XmlAccessorType(XmlAccessType.FIELD) ,控制字段或?qū)傩缘男蛄谢?。FIELD表示JAXB將自動(dòng)綁定Java類中的每個(gè)非靜態(tài)的(static)、非瞬態(tài)的(由@XmlTransient標(biāo) 注)字段到XML。其他值還有XmlAccessType.PROPERTY和XmlAccessType.NONE。
@XmlAccessorOrder,控制JAXB 綁定類中屬性和字段的排序。
@XmlJavaTypeAdapter,使用定制的適配器(即擴(kuò)展抽象類XmlAdapter并覆蓋marshal()和unmarshal()方法),以序列化Java類為XML。
@XmlElementWrapper ,對(duì)于數(shù)組或集合(即包含多個(gè)元素的成員變量),生成一個(gè)包裝該數(shù)組或集合的XML元素(稱為包裝器)。
@XmlRootElement,將Java類或枚舉類型映射到XML元素。
@XmlElement,將Java類的一個(gè)屬性映射到與屬性同名的一個(gè)XML元素。
@XmlAttribute,將Java類的一個(gè)屬性映射到與屬性同名的一個(gè)XML屬性。
三、示例
1、準(zhǔn)備工作
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工具類 * @author zhuc * @create 2013-3-29 下午2:40:14 */ public class JaxbUtil { /** * JavaBean轉(zhuǎn)換成xml * 默認(rèn)編碼UTF-8 * @param obj * @param writer * @return */ public static String convertToXml(Object obj) { return convertToXml(obj, "UTF-8"); } /** * JavaBean轉(zhuǎn)換成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轉(zhuǎn)換成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; } }
非常簡(jiǎn)單易懂,需要注意的是
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
Marshaller.JAXB_FORMATTED_OUTPUT 決定是否在轉(zhuǎn)換成xml時(shí)同時(shí)進(jìn)行格式化(即按標(biāo)簽自動(dòng)換行,否則即是一行的xml)
Marshaller.JAXB_ENCODING xml的編碼方式
另外,Marshaller 還有其他Property可以設(shè)置,可以去查閱api。
2、最簡(jiǎn)單轉(zhuǎn)換
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 下午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 下午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); //默認(rèn)是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); } }
輸出結(jié)果分別為:
<?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、類中包含復(fù)雜對(duì)象的轉(zhuǎn)換
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 下午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 下午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 下午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("管理"); role.setName("班長"); 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>班長</name>"+ " <desc>管理</desc>"+ "</role>"+ "</student>"; Student student = JaxbUtil.converyToJavaBean(str, Student.class); System.out.println(student); } }
輸出結(jié)果分別為:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <student id="12"> <name>test</name> <role> <name>班長</name> <desc>管理</desc> </role> </student> Student [id=12, name=test, role=Role [name=班長, desc=管理]]
4、集合對(duì)象的轉(zhuǎn)換(同樣適用于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 下午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 + "]"; } }
package 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; /** * @author zhuc * @create 2013-3-29 下午2:56:03 */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = { "name", "provCity" }) public class Province { @XmlElement(name = "province_name") private String name; @XmlElement(name = "prov_city") private String provCity; /** * @return the provCity */ public String getProvCity() { return provCity; } /** * @param provCity the provCity to set */ public void setProvCity(String provCity) { this.provCity = provCity; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Province [name=" + name + ", provCity=" + provCity + "]"; } }
package t3; import java.util.ArrayList; import java.util.List; import org.junit.Test; import utils.JaxbUtil; /** * @author zhuc * @create 2013-3-29 下午2:56:11 */ public class JaxbTest3 { /** * @throws JAXBException */ @Test public void showMarshaller() { 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.convertToXml(country); System.out.println(str); } /** * */ @Test public void showUnMarshaller() { 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); } }
輸出結(jié)果分別為:
<?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 [name=中國, provinceList=[Province [name=江蘇省, provCity=南京市], Province [name=浙江省, provCity=杭州市]]]
PS:這里再為大家推薦一款本站相關(guān)的JavaBean在線工具供大家參考使用:
在線JSON轉(zhuǎn)Java Bean代碼工具:
http://tools.jb51.net/code/json2javabean
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
springBoot+mybatis-plus實(shí)現(xiàn)監(jiān)聽mysql數(shù)據(jù)庫的數(shù)據(jù)增刪改
mybatis-plus技術(shù)是簡(jiǎn)化了繁瑣的代碼操作,把增刪改查的語句都內(nèi)置了,直接調(diào)用就可以實(shí)現(xiàn)數(shù)據(jù)庫的增刪改查了,這篇文章主要給大家介紹了關(guān)于springBoot+mybatis-plus實(shí)現(xiàn)監(jiān)聽mysql數(shù)據(jù)庫數(shù)據(jù)增刪改的相關(guān)資料,需要的朋友可以參考下2024-01-01ElasticSearch不停機(jī)重建索引延伸思考及優(yōu)化詳解
這篇文章主要為大家介紹了ElasticSearch不停機(jī)重建索引延伸思考及優(yōu)化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02使用Netty快速實(shí)現(xiàn)一個(gè)群聊功能的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用?Netty?框架開發(fā)一個(gè)?WebSocket?服務(wù)端,從而實(shí)現(xiàn)一個(gè)簡(jiǎn)單的在線聊天功能,感興趣的小伙伴可以了解下2023-11-11Spring Bean初始化及銷毀多種實(shí)現(xiàn)方式
這篇文章主要介紹了Spring Bean初始化及銷毀多種實(shí)現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11java 如何遠(yuǎn)程控制tomcat啟動(dòng)關(guān)機(jī)
這篇文章主要介紹了java 遠(yuǎn)程控制tomcat啟動(dòng)關(guān)機(jī)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04JavaSE中compare、compareTo的區(qū)別
本文主要介紹了JavaSE中compare、compareTo的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05關(guān)于Http持久連接和HttpClient連接池的深入理解
眾所周知,httpclient是java開發(fā)中非常常見的一種訪問網(wǎng)絡(luò)資源的方式了,下面這篇文章主要給大家介紹了關(guān)于Http持久連接和HttpClient連接池的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-05-05