jaxb 序列化java.util.List

jaxb 序列化java.util.List

jaxb序列化java.util.List package cn.outofmem […]

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 names;
 
 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属性的java实例,并将序列化的结果输出到控制台,输出结果如下:



 I'm a string
 I'm also a string.

可以看到names属性被序列化为两个names节点,如果java bean中属性较多的话就会产生混乱,我们可以通过XmlElementWrapper注解来把这两个names节点包装起来,可以通过XmlElement注解修改names节点的名称。如下java代码:

 @XmlElementWrapper(name = "names")
 @XmlElement(name = "item")
 public List getNames() {
  return names;
 }
这样修改之后输出的xml将变为:



 
 I'm a string
 I'm also a string.
 


 
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 names;
 
 @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注解,运行程序的输出如下:



 
 I'm a string
 I'm also a string.
 

 
 
 21
 zhao
 

 
 11
 zhang
 

 

转载来自网络

XML 地图