我想序列化项的arraylist,但它不起作用....
我的项类扩展了 Stuff 类,并且有一些子类。
我的所有类都实现了Serilalizable。
我有这个部分:
try{ // Serialize data object to a file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser")); out.writeObject(myData); out.close(); // Serialize data object to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream() ; out = new ObjectOutputStream(bos) ; out.writeObject(myData); out.close(); // Get the bytes of the serialized object byte[] buf = bos.toByteArray(); } catch (IOException e) { }
我的班级:
public class Stuff implements Serializeable{ .... some protected fields . . } public class Item extends Stuff implements Serializable{ ... .. . } and some subclasses of Item: public class FirstItem extends Item implements Serializable{ ... } public class SecondItem extends Item implements Serializable{ ... } ... I want to serialize an object contains ArrayList of <Item> that has objects of Item's subclasses (FirstItem,SecondItem,...)
我认为信息就足够了......
这只是一个小错误,现在正常工作...... 对不起我的愚蠢问题,我很抱歉。
感谢您的回答。
答案 0 :(得分:5)
您可以像这样序列化ArrayList类
public class MyData implements Serializable {
private long id;
private String title;
private ArrayList<String> tags;
...
public String getTitle() {
}
}
并创建可序列化的
ArrayList<MyData> myData = new ArrayList<MyData>();
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("MyData.ser"));
out.writeObject(myData);
out.close();
// Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(myData);
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
}
答案 1 :(得分:1)
我在这里跳跃,你试图序列化为像json这样的东西?
如果是这样,你可以使用jackson(http://jackson.codehaus.org/)
final ObjectMapper mapper = new ObjectMapper();
try
{
final String jsonString = mapper.writeValueAsString( _integrationSettings );
// do something with the string...
}
catch( IOException e )
{
// use a logger to output error
}
您也可以使用jackson进行反序列化...
此处有一个更详细的示例:http://blog.inflinx.com/2012/05/10/using-jackson-for-javajson-conversion/
注意:您可以对XML执行类似操作。