JAXB2序列化XML
Jaxb2 实现JavaBean与xml互转 http://zhuchengzzcc.iteye.com/blog/1838702
- JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。
- Marshaller接口,将Java对象序列化为XML数据。
- Unmarshaller接口,将XML数据反序列化为Java对象。
- @XmlType,将Java类或枚举类型映射到XML模式类型
- @XmlAccessorType(XmlAccessType.FIELD) ,控制字段或属性的序列化。FIELD表示JAXB将自动绑定Java类中的每个非静态的(static)、非瞬态的(由@XmlTransient标 注)字段到XML。其他值还有XmlAccessType.PROPERTY和XmlAccessType.NONE。
- @XmlAccessorOrder,控制JAXB 绑定类中属性和字段的排序。
- @XmlJavaTypeAdapter,使用定制的适配器(即扩展抽象类XmlAdapter并覆盖marshal()和unmarshal()方法),以序列化Java类为XML。
- @XmlElementWrapper ,对于数组或集合(即包含多个元素的成员变量),生成一个包装该数组或集合的XML元素(称为包装器)。
- @XmlRootElement,将Java类或枚举类型映射到XML元素。
- @XmlElement,将Java类的一个属性映射到与属性同名的一个XML元素。
- @XmlAttribute,将Java类的一个属性映射到与属性同名的一个XML属性。
1、
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转换成xml * 默认编码UTF-8 * @param obj * @param writer * @return */ public static String convertToXml(Object obj) { return convertToXml(obj, "UTF-8"); } /** * JavaBean转换成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转换成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; } }
2、简单转换
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); //默认是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); } }
3、类中包含复杂对象的转换
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); } }
4、集合对象的转换
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); } }
JAXB2序列化XML的更多相关文章
- 对象序列化XML
/// <summary>/// 对象序列化XML/// </summary>/// <param name="type">类型</par ...
- WCF中序列化(XML\JSON\Dt)
序列化 是将对象转换为容易传输的格式的过程.例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象.反之,反序列化根据流重新构造对象. 序列化描述了持久化 ...
- C# 对象 序列化 XML
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...
- C#.NET序列化XML、JSON、二进制微软自带DLL与newtonsoft(json.net)
序列化是将对象转换成另一种格式(XML.json.二进制byte[]) JSON序列化 .NET中有三种常用的JSON序列化的类,分别是: Newtonsoft.Json.JsonConvert类(推 ...
- SharePreference是如何实现的——序列化XML文件
还记得上一篇我们讲到了用SharePreference来存储数据,那么究竟它是如何实现的呢,今天我们就来仔细看看其实现的细节,我们给它一个准确的名字,叫做XML序列化器(XmlSerializer). ...
- C# 序列化xml
把一个类序列化成xml,显示在txtarea,然后在获取txtarea的值进行反序列化成类,因为一个字段的值是url形式的,url里面有这个符号:&,所以反序列化的时候报错了,查了好久才发现是 ...
- 反序列化和序列化xml使用反射处理节点的属性
当一个xml中有大量的属性XmlAttribute需要序列化和反序列化,通常需要复制粘贴大量的如下代码,显得很丑陋,而且容易出错: XmlAttribute attr = Doc.CreateAttr ...
- C#序列化xml,开发常用
序列化操作对于开发人员来说最熟悉不过了. 序列化分为:序列化和反序列化. 序列化名词解释:序列化是将对象状态转换为可保持或传输的格式的过程. 与序列化相对的是反序列化,它将流转换为对象.这两个过程结合 ...
- 如何在IJ中使用Jaxb2通过xml定义生成对应的Java Entity类的文件
#0. 准备要转换的xml文件,在Project视界中,右击这个xml文件,在弹出的菜单上选择“Generate XSD schema from XML File...”, 按默认设置生成xsd文件. ...
随机推荐
- Android Studio的使用(六)
本篇博文介绍如何更新Android Studio. 1.导航栏的Help下拉框可以找到更新的按钮. 2.接下来点击Update and Restart即可 3.有些人说网连不上,但我的就可以,不行的话 ...
- AJAX(XMLHttpRequest)进行跨域请求方法详解(三)
注意:以下代码请在Firefox 3.5.Chrome 3.0.Safari 4之后的版本中进行测试.IE8的实现方法与其他浏览不同. 3,带验证信息的请求 身份验证是Web开发中经常遇到的问题,在跨 ...
- 用DIV+CSS做网页里要设置body和*规定内容
body{}表示是对body标签的设置,就是<html><head></head><body></body></html> 里面 ...
- opentsdb
http://blog.javachen.com/2014/01/22/all-things-opentsdb.html http://blog.csdn.net/bingjie1217/articl ...
- js中将 整数转成字符,,将unicode 编码后的字符还原出来的方法。
一.将整数转成字符: String.fromCharCode(17496>>8,17496&0xFF,19504>>8,19504&0xFF,12848> ...
- Android Studio调试功能使用总结---转
Android Studio调试功能使用总结[转] 这段时间一直在使用Intellij IDEA, 今天把调试区工具的使用方法记录于此. 先编译好要调试的程序. 1.设置断点 选定要设置断点的代码 ...
- GB2312转unicode程序(转)
GB2312转unicode程序 #ifndef UNICODE_H #define UNICODE_H #include <string.h> #ifdef __DEFLINUX_ ...
- 随机获取部分List<Object>集合
随机返回list对象 /** * 返回随机List * @param list 备选 * @param selected 备选数量 * @return */ public List getRandom ...
- js获取屏幕和窗口的信息
<html><script>function a(){document.write("屏幕分辨率为:"+screen.width+"*" ...
- 《accelerated c++》第九章---设计类
本章简单介绍了类的设计,但是包含了一些好的设计原则. 1一些通用的设计原则 (1)一个函数是否设计成成员函数的原则:如果这个函数改变对象的状态,那么这个函数就应该成为这个对象的成员. (2)对于内置类 ...