Action script to string serialization and de-serialization


/ Published in: ActionScript 3
Save to your folder(s)

This snippet shows how to serialize action script object to strings, the serialization method is AMF based, note also that each object must meet three basic rules in order to be serialized properly:
¨1. The constructor must take no arguments
2. Fields must be public or they won’t be saved
3. You must register it with a class alias by calling flash.net.registerClassAlias(aliasString, class).¨
(this is based upon http://www.partlyhuman.com/blog/roger/technique-storing-arbitrary-objects-in-html-links).


Copy this code and paste it in your HTML
  1. package
  2. {
  3. import flash.utils.ByteArray;
  4. import mx.utils.Base64Encoder;
  5. import mx.utils.Base64Decoder;
  6.  
  7. public class SerializationUtils {
  8. public static function serializeToString(value:Object):String{
  9. if(value==null){
  10. throw new Error("null isn't a legal serialization candidate");
  11. }
  12. var bytes:ByteArray = new ByteArray();
  13. bytes.writeObject(value);
  14. bytes.position = 0;
  15. var be:Base64Encoder = new Base64Encoder();
  16. be.encode(bytes.readUTFBytes(bytes.length));
  17. return be.drain();
  18. }
  19.  
  20. public static function readObjectFromStringBytes(value:String):Object{
  21. var dec:Base64Decoder=new Base64Decoder();
  22. dec.decode(value);
  23. var result:ByteArray=dec.drain();
  24. result.position=0;
  25. return result.readObject();
  26. }
  27. }
  28. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.