我在序列化类中的字段时遇到问题,这是 ArrayList 的子类。添加到列表中的项目是序列化的,但字段不是:
@XmlRootElement
public static class NumberedList extends ArrayList<String>{
@XmlAttribute
private int number = 5;
@XmlList
public List<String> getNames(){
return this;
}
public NumberedList(){
add("a");
add("b");
}
}
@XmlRootElement
public static class FieldTest{
@XmlElement
NumberedList list = new NumberedList();
}
public static void main(String[] args) throws Exception{
JAXBContext context = JAXBContext.newInstance(FieldTest.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(new FieldTest(), System.out);
}
//将 NumberedList 序列化为字段的输出:不存在数字字段
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><fieldTest><list>a</list><list>b</list></fieldTest>
奇怪的是,当我将列表添加到 Map 时,我的类中的字段会按照我的预期进行序列化。
@XmlRootElement
public static class NumberedList extends ArrayList<String>{
@XmlAttribute
private int number = 5;
@XmlList
public List<String> getNames(){
return this;
}
public NumberedList(){
add("a");
add("b");
}
}
@XmlRootElement
public static class MapTest{
@XmlElement
Map<Integer, NumberedList> map = Maps.newHashMap();
public MapTest(){
map.put(1, new NumberedList());
}
}
public static void main(String[] args) throws Exception{
JAXBContext context = JAXBContext.newInstance(MapTest.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(new MapTest(), System.out);
}
//在 Map 中序列化 NumberedList 的输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><mapTest><map><entry><key>1</key><value number="5"><names>a b</names></value></entry></map></mapTest>
有任何想法吗?