Flex - 将对象的序列化ArrayCollection保存到文件

时间:2014-09-22 11:30:05

标签: actionscript-3 flex serialization deserialization amf

使用RemoteClass metateg创建类

[RemoteClass]
public class Result 
{
    public function Result(){} 
}

写入文件的功能

public function writeData(object:Object):void
{
    var file:File = File.desktopDirectory.resolvePath("data.txt");
    if (file.exists)
        file.deleteFile();      
    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.WRITE);
    fileStream.writeObject(object);
    fileStream.close();
}

从文件中读取的功能

public function readData():Object
{
    var file:File = File.desktopDirectory.resolvePath("data.txt");
    if(!file.exists) 
        return 0;
    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.READ);
    var obj:Object = fileStream.readObject();
    fileStream.close();
    return obj;
}

申请初始化时的功能

public function initApplication():void
{
    writeData(new Result()); // write object to file.
    var result:Result = readData() as Result; // create Result class object and initializing it data from file
    var array:ArrayCollection = new ArrayCollection(); // create collection and fill it objects of Result class
    array.addItem(new Result());
    array.addItem(new Result());
    array.addItem(new Result());
    writeData(array); // writing collection in file
    var arr:ArrayCollection = readData() as ArrayCollection; // initializing new collecion of collection from file.
}

这是问题。使用Object类型的对象返回集合。 如何获取Result类型对象的集合?

以下的坏方法
for each (var object:Object in arr) 
{
        object = object as Result;
}

1 个答案:

答案 0 :(得分:2)

在序列化/反序列化之前使用registerClassAlias()