1. JAXB的介绍
2. JAXB中的核心类以及相关类介绍
3. JAXB中的常用注解介绍
4. 使用演示展示
首先介绍下什么是JAXB?
JAXB的核心类有如下三个:
JAXBContext类,是应用的入口,用于管理XML/Java绑定信息。
该类不能直接创建,只能使用如下方式进行实例化JAXBContext对象:
static JAXBContext
newInstance(Class... classesToBeBound) Obtain a new instance of a JAXBContext class. | |
static JAXBContext | newInstance(Class[] classesToBeBound, Map<String,?> properties) Obtain a new instance of a JAXBContext class. |
static JAXBContext | newInstance(String contextPath) Obtain a new instance of a JAXBContext class. |
static JAXBContext | newInstance(String contextPath, ClassLoader classLoader) Obtain a new instance of a JAXBContext class. |
static JAXBContext | newInstance(String contextPath, ClassLoader classLoader, Map<String,?> properties) Obtain a new instance of a JAXBContext class. |
Marshaller接口,将Java对象序列化为XML数据。
该类是设置转换为XML数据的熟悉如格式化输出xml,设备xml的编码格式等:
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
Unmarshaller接口,将XML数据反序列化为Java对象。
反序列化java对象需要用到的实例:
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
使用JAXB常用的注解如下:
@XmlType用在class类的注解,常与@XmlRootElement,@XmlAccessorType一起使用。它有三个属性:name、propOrder、namespace,经常使用的只有前两个属性。如:
@XmlType(name = "basicStruct", propOrder = { "intValue", "stringArray", "stringValue" )
在使用@XmlType的propOrder 属性时,必须列出JavaBean对象中的所有属性,否则会报错。
@XmlElement将java对象的属性映射为xml的节点,在使用@XmlElement时,可通过name属性改变java对象属性在xml中显示的名称。如:
@XmlRootElement用于类级别的注解,对应xml的跟元素,常与 @XmlType 和 @XmlAccessorType一起使用。如:
@XmlAccessorType用于指定由java对象生成xml文件时对java对象属性的访问方式。常与@XmlRootElement、@XmlType一起使用。它的属性值是XmlAccessType的4个枚举值,分 别为:
XmlAccessType.FIELD:java对象中的所有成员变量
XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量
XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量
XmlAccessType.NONE:java对象的所有属性都不映射为xml的元素
注意:@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在 private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限 为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。
@XmlAccessorOrder用于对java对象生成的xml元素进行排序。它有两个属性值:
AccessorOrder.ALPHABETICAL:对生成的xml元素按字母书序排序
XmlAccessOrder.UNDEFINED:不排序
@XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。
@XmlJavaTypeAdapter常用在转换比较复杂的对象时,如map类型或者格式化日期等。使用此注解时,需要自己写一个adapter类继承XmlAdapter抽象类,并实现里面的方法。
@XmlJavaTypeAdapter(value=xxx.class),value为自己定义的adapter类
XmlAdapter如下:
public abstract class XmlAdapter<ValueType,BoundType> { // Do-nothing constructor for the derived classes. protected XmlAdapter() {} // Convert a value type to a bound type. public abstract BoundType unmarshal(ValueType v); // Convert a bound type to a value type. public abstract ValueType marshal(BoundType v); }
演示DEMO
工具类:
package com.lgy.xml;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
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);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
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;
}
}
package com.lgy.xml;
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;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="xmlDemo")
@XmlType(propOrder = { "author", "calendar", "price"})
public class XmlDemo {
@XmlElement(required = true)
private String author;
@XmlElement(name = "price_1", required = true)
private float price;
@XmlElement
private Date calendar;
@XmlAttribute
private Integer id;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Date getCalendar() {
return calendar;
}
public void setCalendar(Date calendar) {
this.calendar = calendar;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "XmlDemo [author=" + author + ", price=" + price + ", calendar=" + calendar + ", id=" + id + "]";
}
}
package com.lgy.xml;
import java.util.List;
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;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Generators")
@XmlType(propOrder = {"generatorsGroups"})
public class Generators {
@XmlAttribute
private Integer id;
@XmlElement(required = true)
private List<GeneratorsGroup> generatorsGroups;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<GeneratorsGroup> getGeneratorsGroups() {
return generatorsGroups;
}
public void setGeneratorsGroups(List<GeneratorsGroup> generatorsGroups) {
this.generatorsGroups = generatorsGroups;
}
@Override
public String toString() {
return "Generators [id=" + id + ", generatorsGroups=" + generatorsGroups + "]";
}
}
package com.lgy.xml;
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 = {"test"})
public class GeneratorsGroup {
@XmlElement(required = true)
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override
public String toString() {
return "GeneratorsGroup [test=" + test + "]";
}
}