Reputation: 618
Having problem reading bytearray of custom objects. Any help is appreciated
public class CustomObject extends Object {
public function CustomObject() {
public var _x:Number = 100
public var _y:Number = 10
public var _z:Number = 60
}
}
var cObj:CustomObject = new CustomObject()
var bytes:ByteArray = new ByteArray()
bytes.writeObject(cObj)
bytes.compress()
//read
try { bytes.uncompress() } catch (e:Error) { }
var obj:CustomObject = bytes.readObject() as CustomObject
trace(obj) // null why?!
trace(obj._z) // Obviously - TypeError: Error #1009: Cannot access a property or method of a null object reference.
Upvotes: 6
Views: 11516
Reputation: 1
To serialize custom classes to the ByteArray
, you must put registerClassAlias
in the constructor of the class calling the byteArray.writeObject()
function.
If you don't, your custom class will be serialized as Object type. I was calling registerClassAlias
in the serialize function below and my custom class keeps getting serialized as Object
until I moved the registerClassAlias
to the constructor.
public class MyClass{
public function MyClass(){
registerClassAlias("com.myclass", MyClass); // Ok, serializes as MyClass
serialize( new MyClass() );
}
private function serialize( _c:MyClass ){
var byteArray:ByteArray = new ByteArray();
byteArray.writeObject( _c );
//registerClassAlias("com.myclass", MyClass); Not ok, serialized as Object
EncryptedLocalStorage.setItem('key', byteArray);
}
}
Upvotes: 0
Reputation: 9572
Your CustomObject class is wrong , it should throw an error actually , it should be this instead
public class CustomObject { public var _x:Number = 100 public var _y:Number = 10 public var _z:Number = 60 public function CustomObject() { } }
Edit:
Sounds like macke has a point, because this works...
//read try { bytes.uncompress() } catch (e:Error) { } var obj:Object = bytes.readObject(); trace(obj) // [object Object] trace(obj._z) // 60
Upvotes: 1
Reputation: 4994
What you want to do is use the registerClassAlias method to register type information along with the data. That way Flash will know how to serialize/deserialize your object. Here's some sample code from Adobe's documentation:
registerClassAlias("com.example.eg", ExampleClass);
var eg1:ExampleClass = new ExampleClass();
var ba:ByteArray = new ByteArray();
ba.writeObject(eg1);
ba.position = 0;
var eg2:* = ba.readObject();
trace(eg2 is ExampleClass); // true
It should be noted that all types that should be serialized must be registered for the type information to be saved. So if you have another type that is referenced by your type, it too must be registered.
Upvotes: 12
Reputation: 9897
Look at object that ByteArray.readObject()
returns. You'll probably see that all properties are there, but type information is lost. So, you can solve this by creating some
public static function fromObject(value:Object):CustomObject {
var result:CustomObject = new CustomObject();
result._x = value._x;
//and so on...
return result;
}
Upvotes: 0