[英]How to serialize ArrayList of objects?
我想序列化Item的數組列表,但是不起作用...。
我的Item類擴展了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,...)
我認為信息足夠...
這只是一個小錯誤,現在可以正常使用...對於我的愚蠢問題,我們深表歉意。
謝謝您的回答。
您可以像這樣序列化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) {
}
我在這里取得了飛躍,您正在嘗試序列化為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
}
您還可以與傑克遜進行反序列化...
此處有一個更詳細的示例: http : //blog.inflinx.com/2012/05/10/using-jackson-for-javajson-conversion/
注意:您可以對XML做類似的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.