使用 List 成员序列化对象
给定以下类:
public class Container {
private List<SomeData> list;
// public getter & setter for list
}
public class SomeData {
private String data;
// public getter & setter for data
}
当我运行以下代码时:
import java.beans.XMLEncoder;
import java.io.FileOutputStream;
SomeData someData1 = new SomeData();
SomeData someData2 = new SomeData();
someData1.setData("data1");
someData2.setData("data2");
List<SomeData> data = new ArrayList<SomeData>();
data.add(someData1);
data.add(someData2);
Container container = new Container();
container.setList(data);
FileOutputStream os = new FileOutputStream("c:\test.xml");
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(container);
encoder.close();
当我查看“test.xml”时,只有容器对象的数据,列表中的 SomeData 对象没有任何数据(即字符串“data1”和“data2”) "):
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_22" class="java.beans.XMLDecoder">
<object class="Container">
<void property="container">
<object class="java.util.ArrayList">
<void method="add">
<object class="SomeData"/>
</void>
<void method="add">
<object class="SomeData"/>
</void>
</object>
</void>
</object>
</java>
如何序列化“容器”和存储在“容器”列表中的 SomeData 对象?
Given the following classes:
public class Container {
private List<SomeData> list;
// public getter & setter for list
}
public class SomeData {
private String data;
// public getter & setter for data
}
When I run the following code:
import java.beans.XMLEncoder;
import java.io.FileOutputStream;
SomeData someData1 = new SomeData();
SomeData someData2 = new SomeData();
someData1.setData("data1");
someData2.setData("data2");
List<SomeData> data = new ArrayList<SomeData>();
data.add(someData1);
data.add(someData2);
Container container = new Container();
container.setList(data);
FileOutputStream os = new FileOutputStream("c:\test.xml");
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(container);
encoder.close();
When I review 'test.xml', there is only data for the container object, and nothing for the SomeData objects in the list (i.e. the strings "data1" & "data2"):
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.6.0_22" class="java.beans.XMLDecoder">
<object class="Container">
<void property="container">
<object class="java.util.ArrayList">
<void method="add">
<object class="SomeData"/>
</void>
<void method="add">
<object class="SomeData"/>
</void>
</object>
</void>
</object>
</java>
How can I serialize 'container' and the SomeData objects stored in the list within 'container'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要我为 SomeData.data 提供根据 java beans 命名约定命名的 getter,代码就可以正常工作:
如果我更改 getter 的名称,序列化将无法工作。
The code works fine for me as long as I provide getter for SomeData.data named according to the java beans naming convention:
If I change the name of the getter, the serialization wont work.