【问题标题】:How to serialize ArrayList of objects?如何序列化对象的ArrayList?
【发布时间】:2014-07-10 17:27:01
【问题描述】:

我想序列化 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,...)

我认为信息已经足够...

这只是一个小错误,现在可以正常工作... 很抱歉我的愚蠢问题。

感谢您的回答。

【问题讨论】:

  • 能否请您发布您尝试但不起作用的代码,以便我们能够更具体地回答您的问题。
  • 你如何序列化它(你使用什么库)?你的课程是什么样的?你需要在它们中序列化什么? “不起作用”是什么意思?
  • 请#define“不起作用”。它会抛出异常吗?反序列化成废话?放火烧裤子?
  • “不起作用”不是问题描述。再试一次。

标签: java serialization arraylist subclass extend


【解决方案1】:

你可以像这样序列化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) {
}

【讨论】:

  • 为什么不用设置每个列表的ID?
【解决方案2】:

我在这里飞跃,您正在尝试序列化为 json 之类的东西?

如果是这样,您可以使用杰克逊 (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 执行类似操作。

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 2013-01-18
    • 2015-03-18
    • 2014-07-10
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多