Serialize Flex Objects to Save/Restore Application

2019-08-07 16:42发布

问题:

Is it possible to serialize a hierarchy of objects in Flex, send the binary data to a URL for storage/retrieval on/from a server, and deserialize the data to restore the objects' original state?

I know it's possible to convert the objects into an XML format (haven't tried it yet), but I'm hoping to avoid parsing XML and rebuilding the objects manually. It would be nice to have functionality which can serialize/deserialize objects to a simple binary format (I did something similar in the past in Java, though not quite as easily as I would have liked). The 'eval' function in Perl is similar to what I'm looking for, sans saving code, of course.

In pseudo-code, here's what I would like to do:

private var contentToSave:HBox = new HBox();

private function saveState(event:Event):void {
    var toSave:HBox = this.contentToSave;
    var data:? = /* serialize 'toSave' ActionScript classes to binary data*/;
    sendDataToServer(data, filename);
}
private function restoreState(filename):void {
    var data:? = getDataFromServer(filename);
    var savedData:HBox = /* deserialize binary 'data' to ActionScript classes */;
    this.contentToSave = savedData;
}

回答1:

Try the JSON based serialization package in ascorelib.

[...]but I'm hoping to avoid parsing XML and rebuilding the objects manually

AS handles XML just like any other native type. Rest assured. XML is the preferred way of dealing with data you will be pulling off and putting back on a server. Of course, the ascorelib gives you a JSON class -- so you may want to look at that as well.

The 'eval' function in Perl is similar to what I'm looking for, sans saving code, of course.

IIRC, eval is part of the ECMAScript specification (and you will find it in Javascript). But not in AS3.0. It was there to a certain extent in some previous version(s?) but is no longer supported.



回答2:

Take a look at ByteArray.writeObject(). which saves the passed object in AMF format into the byte array. I have not used this function too much, I don't exactly know what kind of objects it can serialize, but definitely not all.