当前位置: 移动技术网 > IT编程>开发语言>Java > Jaxb2实现JavaBean与xml互转的方法详解

Jaxb2实现JavaBean与xml互转的方法详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲述了jaxb2实现javabean与xml互转的方法。分享给大家供大家参考,具体如下:

一、简介

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注解。

二、重要概念

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;
  }
}

非常简单易懂,需要注意的是

marshaller.setproperty(marshaller.jaxb_formatted_output, true);
marshaller.setproperty(marshaller.jaxb_encoding, encoding);

marshaller.jaxb_formatted_output 决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)

marshaller.jaxb_encoding xml的编码方式

另外,marshaller 还有其他property可以设置,可以去查阅api。

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);
  }
}

输出结果分别为:

<?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、类中包含复杂对象的转换

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);
  }
}

输出结果分别为:

<?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、集合对象的转换(同样适用于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);
  }
}

输出结果分别为:

<?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:这里再为大家推荐一款本站相关的javabean在线工具供大家参考使用:

在线json转java bean代码工具:

希望本文所述对大家java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网