首页 >后端开发 >XML/RSS教程 >Jaxb2实现Bean与xml互转的示例代码详解

Jaxb2实现Bean与xml互转的示例代码详解

黄舟
黄舟原创
2017-03-31 14:40:072138浏览

一、重要类说明

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、JavaBean

import java.util.Date;
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;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import com.tzz.util.xml.JaxbDateSerializer;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "country")
@XmlType(propOrder = { "id", "createDate", "name", "provinceList" })
public class Country {

	private Integer id;
	@XmlJavaTypeAdapter(JaxbDateSerializer.class)
	private Date createDate;
	@XmlElement(name = "name")
	private String name;
	@XmlElementWrapper(name = "provinces")
	@XmlElement(name = "province")
	private List<Province> provinceList;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Date getCreateDate() {
		return createDate;
	}

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<Province> getProvinceList() {
		return provinceList;
	}

	public void setProvinceList(List<Province> provinceList) {
		this.provinceList = provinceList;
	}
}
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "provCity" })
public class Province {

	@XmlElement(name = "name")
	private String name;
	@XmlElement(name = "provCity")
	private String provCity;

	public String getProvCity() {
		return provCity;
	}

	public void setProvCity(String provCity) {
		this.provCity = provCity;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 2、转化工具类

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * Jaxb 2.0
 *
 */
public class JaxbXmlUtil {

	@SuppressWarnings("unchecked")
	public static <T> T xmlToBean(String xml, Class<T> beanClass) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(beanClass);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			T user = (T) unmarshaller.unmarshal(new StringReader(xml));
			return user;
		} catch (JAXBException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**Bean转XML*/
	public static String beanToXml(Object obj) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			//决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			//Marshaller.JAXB_ENCODING xml的编码方式
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

 3、测试类

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.tzz.test.util.xml.entity.Country;
import com.tzz.test.util.xml.entity.Province;
import com.tzz.util.xml.JaxbXmlUtil;

public class TestJaxbBeanToXmlUtil {

	@Test
	public void testBeanToXml() {
		Country country = new Country();
		country.setId(1);
		country.setCreateDate(new Date());
		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 xml = JaxbXmlUtil.beanToXml(country);
		System.out.println(xml);
	}

	@Test
	public void testXmlToBean() {
		String xml = "<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39; ?>" 
				+ "<country>" 
				+ "<id>1</id>"
				+ "<createDate>2016-03-10 09:36:01</createDate>" 
				+ "<name>中国</name>" 
				+ "<provinces>" 
				+ "<province><name>广东省</name><provCity>广州市</provCity></province>" 
				+ "<province><name>湖南省</name><provCity>长沙市</provCity></province>" 
				+ "</provinces>" 
				+ "</country>";
		Country country = JaxbXmlUtil.xmlToBean(xml, Country.class);
		System.out.println(country.getId() + "--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(country.getCreateDate()) + "--" + country.getName());
		for (Province p : country.getProvinceList()) {
			System.out.println(p.getName() + "---" + p.getProvCity());
		}
	}
}

 4、测试结果

 4.1、运行testBeanToXml方法

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<country>
    <id>1</id>
    <createDate>2016-03-10 05:24:57</createDate>
    <name>中国</name>
    <provinces>
        <province>
            <name>广东省</name>
            <provCity>广州市</provCity>
        </province>
        <province>
            <name>湖南省</name>
            <provCity>长沙市</provCity>
        </province>
    </provinces>
</country>

  4.2、运行testXmlToBean方法

1--2016-03-10 09:36:01--中国
广东省---广州市
湖南省---长沙市

以上是Jaxb2实现Bean与xml互转的示例代码详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn