序列化对象中的对象列表

时间:2014-02-11 11:02:40

标签: java jaxb

我有两个定义如下的java类

public class Field {
    public String fieldName;        
}
public class Record {
    public String name;
    public List<Field> fieldList;
}

我尝试使用jaxb序列化Record对象:

JAXBContext jaxbContext = JAXBContext.newInstance(Record.class);
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(new JAXBElement(new QName("", Record.class.getSimpleName()),
                          Record.class, record),
          serializedValue);

我期待对象按如下方式进行序列化

<Record>
  <name>Test</name>
  <fieldList>
    <Field>
      <fieldName>Test1</fieldName>
    </Field>
  </fieldList>
</Record>

但我得到xml如下

<Record>
  <name>Test</name>
  <fieldList>
    <fieldName>Test1</fieldName>
  </fieldList>
</Record>

为什么会这样?如何在序列化的xml中显示Field标记?

1 个答案:

答案 0 :(得分:1)

每当你有一个List或Set时,你必须声明两个标签 @XmlElementWrapper @XmlElement : -

public class Record {
    public String name;
    public List<Field> fieldList;


    @XmlElementWrapper(name = "fieldList")
    // XmlElement sets the name of the entities in collection
    @XmlElement(name = "Field")
   public void setFieldList(List<Field> fieldList)
  {
    this.fieldList = fieldList;
  }


}