例子:
@XmlAccessorType(XmlAccessType.FIELD)
String name=”CY”;
}
public static void main(String[] args){
JAXBContent context = JAXBContent.newInstance(Boy.class);
Marsheller marsheller = context.createMarsheller();
UnMarsheller unmarsheller = context.createUnMarsheller();
Boy boy = new Boy();
marsheller.marshel(boy,System.out);
System.out.println();
String xml=”David”;
Boy boy2 = (Boy)unmarsheller.unmarshel(new StringReader(xml));
System.out.println(boy2.name);
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>CY
David
先是marshall成 xml文件,
@XmlAccessorType(XmlAccessType.FIELD) --> @XmlAccessorType(XmlAccessType.PROPERTY)
所以再运行的结果是:
CY
-----------------------------------------------------
在 改动一 的基础上,给name属性添加 get set 方法。 再运行,结果为:
David
由此 可见 @XmlAccessorType 这个annotation 的作用。
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Boy {
String name = "CY";
int age = 10;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@XmlRootElement // bixude
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Boy {
String name = "CY";
@XmlElement
int age = 10;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>10 CY
David
对于根元素,可以设置属性:
这样,在生成的xml文件中, 标签 就会变为 标签。并且加上一个命名空间。
下面解释 @XmlJavaTypeAdaptor 的作用。
private Address address; // 是一个接口
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
所以 这里要加上 @XmlJavaTypeAdapter(AddressAdapter.class)
这个类会返回Address接口的一个具体实现类的对象。
这 就是 @XmlJavaTypeAdapter 的作用
@XmlType
默认情况下,Jaxb编组出来的xml中的字段顺序是随机的,你可以使用@XmlType的propOrder属性
来指定序列化的顺序。
定义java类时,使用@XmlType(propOrder = { "id", "name", "age","book"})指定输出顺序。
package step2;
import java.util.Set;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
@XmlType(propOrder = { "id", "name", "age","book"})
public class Customer {
String name;
int age;
int id;
Set book;
@XmlElement(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement(name="age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@XmlElement(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Customer [id=" + id + ",name=" + name + ",age=" + age + ",book=" + book + "]";
}
@XmlElementWrapper(name="books")
@XmlElement(name="book")
public Set getBook() {
return book;
}
public void setBook(Set book) {
this.book = book;
}
}
输出的xml:
注:
1.对于@XmlElementWrapper标注的属性,不能出现在@XmlType的propOrder列表中。
2.对于所有@XmlElement标注过的属性,必须出现在@XmlType的propOrder列表中。