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. Junit单元测试的简单使用(主要是在spring框架下的项目)

    首先是解释什么是单元测试,单元测试是指对于一个大型项目里,对于单一模块或者单一接口的测试. 然后解释为什么要写单元测试,首先对于一个大型的项目,如果你每次都要重启一遍服务器调页面或者接口的bug,那就 ...

  2. ViewPager滑动标签-PagerSlidingTabStrip的使用

    有篇博客写的已经非常详细,所以不再写了.主要在于导入这个Library,导入Library看自己的笔记 博客地址:http://doc.okbase.net/HarryWeasley/archive/ ...

  3. jq的事件冒泡

    在页面上可以有多个事件,也可以多个元素响应同一件事, 事件冒泡引发的问题: 有些时候不想动用的事件,却因为事件冒泡而触发 解决问题: 1.事件对象 由于IE-DOM和标准的DOM实现事件对象的方法各不 ...

  4. eclipse myeclipse修改工作区间 an error has occurred. see error log for more details. java.lang.nullpointerexception 问题解决

    解决办法:修改项目工作空间. 修改工作空间,以前打开myEclipse时知道怎么改!现在只有找配置文件了! 步骤: MyEclipse 5.1.1 GA----->Eclipse-----> ...

  5. 解决MyEclipse吃内存以及卡死的方法 (转)

    前言:MyEclipse5.5 大小 139M:MyEclipse6.5 大小 451M:MyEclipse7.0 大小 649M!下载服务器又是国外的...下载速度累人也就罢了,只要你工作性能一流. ...

  6. 转 ogg组件介绍

    应用场景:数据分发   ogg的组件: (1) OGG 程序和工具说明 convchk   转换ogg版本的信息 ,该程序可以将checkpoint files 转换成新版本: convprm :OG ...

  7. 安卓EditText按钮

    main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:and ...

  8. css3的apprearance属性(转)

    appearance使用方法: .elmClass{ -webkit-appearance: value; -moz-appearance: value; appearance: value; } 接 ...

  9. python赋值和拷贝----一切皆对象,参数皆引用

    摘要: 1 python中的一切事物皆为对象,并且规定参数的传递都是对象的引用. 2  python参数传递都是"传对象引用"方式.实际上相当于c++中传值和传引用的结合. 3 如 ...

  10. web容器启动顺序

    web容器启动顺序: 第一:context-param 第二:Listerer 第三:Filter 第四:servlet