使用XStream序列化为XML但不获取所有字段

时间:2012-04-26 20:59:06

标签: java xml serialization xstream

我有一个名为Lookup的类,它有两个属性:

public class Lookup {

    private String surveyName;
    private String GUID;    

    public Lookup(String name, String guid){
        this.surveyName = name;
        this.GUID = guid;   
    }

}

在另一个类中,我有一个Lookup列表,我正在尝试序列化并保存到文件中。这就是我的做法:

List<Lookup> lookup = new ArrayList<Lookup>();
lookup.add(new Lookup("foo","bar"));
XStream serializer = new XStream();
serializer.alias("Lookups",List.class);
String xml = serializer.toXML(lookup);

我最终得到的XML是:

<Lookups>
  <Lookup>
    <GUID>bar</GUID>
  </Lookup>
</Lookups>

如您所见,它仅序列化了字段GUID,但未序列化字段surveyName。为什么忽略那个领域?

2 个答案:

答案 0 :(得分:1)

您确定不要在其他地方修改Lookup变量吗?这段代码运行良好

public class Test {
    public static void main(String[] args) {
        List<Lookup> lookup = new ArrayList<Lookup>();
        lookup.add(new Lookup("foo","bar"));
        XStream serializer = new XStream();
        serializer.alias("Lookups",List.class);
        String xml = serializer.toXML(lookup);
        System.out.println(xml);
    }
}
class Lookup {
    private String surveyName;
    private String GUID;    

    public Lookup(String name, String guid){
        this.surveyName = name;
        this.GUID = guid;   
    }
}

输出:

<Lookups>
  <Lookup>
    <surveyName>foo</surveyName>
    <GUID>bar</GUID>
  </Lookup>
</Lookups>

答案 1 :(得分:0)

傻了我,错误完全在我身上。字段name正在接收一个空字符串,因此XStream必须忽略它。