如何对ArrayList(Object)进行序列化/反序列化

14

我有一个 ArrayList<ItemList>

其中 ItemList 为:

public class ItemList {
    public ArrayList<Item> it = new ArrayList<Item>();
    public String name = "";

    public ItemList() {
    }
}

该项的值为:

public class Item {
    public String name = "";
    public int count = 0;

    public Item() {
    }
}

我尝试对这个列表进行序列化:

try {
            FileOutputStream fileOut = new FileOutputStream(sdDir + serFile);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(List_Of_Lists);
            out.close();
            fileOut.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

我认为它是有效的,因为我在文件夹中找到了这个文件。

但我无法将文件反序列化为ArrayList<ItemList>

代码:

        try {
            FileInputStream fileIn = new FileInputStream(sdDir + serFile);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            List_Of_Lists = (ArrayList<ItemList>) in.readObject(); 
            Log.i("palval", "dir.exists()");
            in.close();
            fileIn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

如何反序列化这个 ArrayList<ItemList>?我总是遇到 IOException。


请发布完整的异常堆栈跟踪。 - Tomer
你是只序列化ArrayList中的“it”变量还是整个ItemList类? - prashant
我总是抓住IOException。但是你有阅读它包含的信息吗?它包含了答案。 - user207421
3个回答

13

您的ItemItemList类需要实现Serializable


什么是实现Parcelable接口?它能同时实现Serializable接口吗? - the_prole
@the_prole 我不确定你所说的“什么是item implement parcelable?”的意思。关于“它是否可以同时实现Serializable”,可能是可以的,因为类可以实现许多接口,并且Serializable并没有引入任何新方法,因此不应该有任何冲突。 - Pshemo
抱歉,我的意思是,如果该项已经实现了Parcelable接口呢? - the_prole
我不能确定,因为我不是Android开发人员。但如果我需要猜测的话,我会说由于Serializable没有引入任何方法(它是标记接口),所以你应该没问题(只需使用你想要的机制,一个在Parcelable中定义的或者使用Serializable中的)。 - Pshemo
@the_prole 但这只是某个从未在Android上开发过的人的意见,所以我可能是错的。无论如何,我的答案基于假设,在Android中ObjectOutputStream使用涉及Serializable的机制(到目前为止我没有收到任何抱怨,所以我认为我是正确的),这就是为什么我指出了那个接口(直到现在我也不知道Parcelable的存在)。 - Pshemo

0
如果您已经创建了子类,则在父类中添加serializable方法,它将删除错误。

-1

我假设您已经序列化了ItemList而不是Item.....

ArrayList<ItemList> arr = (ArrayList<ItemList>) in.readObject();

for (ItemList a : arr) 
   {
        // In this loop by iterating arr, you will get the whole List of ItemList

   }

好的,请尝试并告诉我结果。实际上,我没有你的完整代码,所以很难猜测。 - Kumar Vivek Mitra
项(Item)和项列表(ItemList)需要实现Serializable接口。 - Val

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接