jaxb序列化java.util.List
2014-05-06
jaxb序列化java.util.List
package cn.outofmemory.jaxb;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
public class JAXBDemo {
private List
public List getNames() {
return names;
}
public void setNames(List names) {
this.names = names;
}
public static void main(String[] args) {
List list = new ArrayList();
list.add("I'm a string");
list.add("I'm also a string.");
JAXBDemo demo = new JAXBDemo();
demo.setNames(list);
JAXB.marshal(demo, System.out);
}
}
上述代码中,我们序列化一个包含List
可以看到names属性被序列化为两个names节点,如果java bean中属性较多的话就会产生混乱,我们可以通过XmlElementWrapper注解来把这两个names节点包装起来,可以通过XmlElement注解修改names节点的名称。如下java代码:
@XmlElementWrapper(name = "names")
@XmlElement(name = "item")
public List
return names;
}
这样修改之后输出的xml将变为:
jaxb序列化自定义的java pojo list
在JAXBdemo类中添加自定义类Person,并添加persons的属性。
package cn.outofmemory.jaxb;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
public class JAXBDemo {
private List
@XmlElementWrapper(name = "names")
@XmlElement(name = "item")
public List getNames() {
return names;
}
public void setNames(List names) {
this.names = names;
}
public static void main(String[] args) {
List list = new ArrayList();
list.add("I'm a string");
list.add("I'm also a string.");
JAXBDemo demo = new JAXBDemo();
demo.setNames(list);
List persons = new LinkedList();
persons .add(new Person("zhao", 21));
persons.add(new Person("zhang", 11));
demo.setPersons(persons);
JAXB.marshal(demo, System.out);
}
public static class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person() {}
public Person(String name_, int age_) {
this.name = name_;
this.age = age_;
}
}
private List persons;
@XmlElementWrapper(name="persons")
@XmlElement(name="person")
public List getPersons() {
return persons;
}
public void setPersons(List persons) {
this.persons = persons;
}
}
对于persons属性,我们同样添加了XmlElementWrapper和XmlElement注解,运行程序的输出如下:
转载来自网络