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的更多相关文章

  1. 对象序列化XML

    /// <summary>/// 对象序列化XML/// </summary>/// <param name="type">类型</par ...

  2. WCF中序列化(XML\JSON\Dt)

    序列化 是将对象转换为容易传输的格式的过程.例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象.反之,反序列化根据流重新构造对象. 序列化描述了持久化 ...

  3. C# 对象 序列化 XML

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  4. C#.NET序列化XML、JSON、二进制微软自带DLL与newtonsoft(json.net)

    序列化是将对象转换成另一种格式(XML.json.二进制byte[]) JSON序列化 .NET中有三种常用的JSON序列化的类,分别是: Newtonsoft.Json.JsonConvert类(推 ...

  5. SharePreference是如何实现的——序列化XML文件

    还记得上一篇我们讲到了用SharePreference来存储数据,那么究竟它是如何实现的呢,今天我们就来仔细看看其实现的细节,我们给它一个准确的名字,叫做XML序列化器(XmlSerializer). ...

  6. C# 序列化xml

    把一个类序列化成xml,显示在txtarea,然后在获取txtarea的值进行反序列化成类,因为一个字段的值是url形式的,url里面有这个符号:&,所以反序列化的时候报错了,查了好久才发现是 ...

  7. 反序列化和序列化xml使用反射处理节点的属性

    当一个xml中有大量的属性XmlAttribute需要序列化和反序列化,通常需要复制粘贴大量的如下代码,显得很丑陋,而且容易出错: XmlAttribute attr = Doc.CreateAttr ...

  8. C#序列化xml,开发常用

    序列化操作对于开发人员来说最熟悉不过了. 序列化分为:序列化和反序列化. 序列化名词解释:序列化是将对象状态转换为可保持或传输的格式的过程. 与序列化相对的是反序列化,它将流转换为对象.这两个过程结合 ...

  9. 如何在IJ中使用Jaxb2通过xml定义生成对应的Java Entity类的文件

    #0. 准备要转换的xml文件,在Project视界中,右击这个xml文件,在弹出的菜单上选择“Generate XSD schema from XML File...”, 按默认设置生成xsd文件. ...

随机推荐

  1. 编译filezilla

    编译zilla的时候,需要用到与mysql连接的地方(这里先忽略zila的编译) VC听过mysql connector c++, 下载了1.1.3版本,然后飞安装包,之后从官网上下载boost 把库 ...

  2. HTTP状态码 - HTTP Status Code

    HTTP Status Code 常见的状态码: HTTP: Status 200 – 服务器成功返回网页HTTP: Status 404 – 请求的网页不存在HTTP: Status 503 – 服 ...

  3. php的header函数之设置content-type

    //定义编码 header( 'Content-Type:text/html;charset=utf-8 '); //Atom header('Content-type: application/at ...

  4. 【转】Apache 关于 mod_rewrite 遇到 %2F或%5C (正反斜杠)等特殊符号导致URL重写失效出现404的问题

    .htaccess 文件 <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d Rew ...

  5. 使用Word API打开Word文档 ASP.NET编程中常用到的27个函数集

    使用Word API(非Openxml)打开Word文档简单示例(必须安装Word) 首先需要引入参照Microsoft.Office.Interop.Word 代码示例如下: public void ...

  6. 2016沈阳网络赛 QSC and Master

    QSC and Master Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) ...

  7. PAT (Advanced Level) 1075. PAT Judge (25)

    简单模拟题. 注意一点:如果一个人所有提交的代码都没编译通过,那么这个人不计排名. 如果一个人提交过的代码中有编译不通过的,也有通过的,那么那份编译不通过的记为0分. #include<cstd ...

  8. FOJ 2206 函数求解

    水题 /* *********************************************** Author :Zhou Zhentao Email :774388357@qq.com C ...

  9. P3P解决cookie存取的跨域问题

    最近在做一个流量统计的东西的时候,偶然发现IE在对iframe里面的页面写Cookie的时候有一些安全限制,导致读取Cookie不成功,找了好长时间的解决办法,重要找到如下的办法: 1.页面里的COO ...

  10. CodeForces 610A Pasha and Stick

    #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using ...