Serializing object using messagepack and as3 - actionscript-3

This is a vary simple question, but can't find any docs on it.
I have a simple class:
public class User
{
public var name:String;
public var age:int;
}
I would like to serialize it using this:
var user:User = new User();
user.age = 15;
user.name = "mike";
//now serialize
var bytes:ByteArray = MessagePack.encoder.write(vo);
But I get an error:
Error: MessagePack handler for type base not found
How do I let MessagePack know what the User class is, how to serialize it?

MessagePack doesn't look like being able to serialize Class, like most serializer.
I suggest you to add a toObject method to your User class :
public function toObject():Object
{
return {age:this.age, name:this.name}:
}
Then you can serialize your user :
var bytes:ByteArray = MessagePack.encoder.write(user.toObject());
You can also add a static fromObject method which takes an object and returns a new User initialized with this object.
static public function fromObject(o:Object):User
{
var u = new User();
u.age = o.age;
u.name = o.name;
return u;
}

Related

Does Flash have a method that does the reverse of toString?

When using ObjectUtil there is a method called, toString() that takes an object. If you pass it a class named, "Person" it will return the string "[class Person]".
var person:Person = new Person();
trace(ObjectUtil.toString(person));//UPDATE I'm not using ObjectUtil.toString()
// traces [class Person]
Is there a toObject() method? Something that takes the same format toString outputs and creates an instance like so:
var person:Person = ObjectUtil.toObject("[class Person]");
UPDATE:
Sorry. This is incorrect. I thought I was using ObjectUtil.toString(). I was not. When I use that method it returns something like:
(com.printui.assets.skins::fontList)#0
accessibilityDescription = ""
accessibilityEnabled = true
accessibilityImplementation = (null)
In my code somewhere it is returning "[class Person]" like I was described. This is the line:
var currentValue:* = target[property];
popUpValueInput.text = currentValue;
I thought it was using instance.toString() but toString() is not returning anything close to that:
var f:fontList = new fontList();
var f1:fontList = new fontList();
trace("" + f);
trace("" + f1);
trace(f1.toString());
Results in:
fontList2
fontList5
fontList5
In general you should do this:
In your Person class add this method:
public function toString():String
{
return "Person" ;
}
So to make an instance of the class by name use this code:
var p = new (getDefinitionByName( ObjectUtils.toString(person)))
or it can be used a regex in general for all classes (thanks to 1.21 gigawatts ):
var p = new (getDefinitionByName( ObjectUtil.toString(Person).match(/\((.*)\)/)[1] ) );

Classes vs Objects? as3

I creat two people that are instances of the Person Class
var personOne = new Person;
var personTwo = new Person;
later I create an Object called Chuck;
var Chuck = {age:32, name:"Chuck"}
Now I want to make personOne be a "person" with the properties of "chuck:Object";
Cannot convert Object to Display Object. // Output
If you want to set properties of an object when it is created, you can let the constructor accept them as parameters.
For example:
package
{
public class Person
{
private var _age:uint, _name:String;
public function Person (age:uint, name:String)
{
_age = age;
_name = name;
}
}
}
You use it like so:
var chuck:Person = new Person(32, "Chuck");
This is probably not what you need, but it is what you asked.
var personOne :Person = new Person();
var object:Object = { age:23, name:"efefw" };
for (var prop:String in object)
{
personOne[prop] = object[prop];
}
This will only work for public properties.

parse JSON object to custom class object in action script 3

I want to parse JSON string to some my custom object in Action script 3. Is there some libs to do this. Or any ideas how can I make this. Thanx!
Here is an example what I want to receive:
{
"result":{
"birthday_at":"0000-00-00",
"first_name":"Myname1",
"level":5,
"last_name":"MySurname",
"gender":0
},
"cmd":"INFO",
"service":{
"code":0,
"error_desc":""
}
}
and class UserInfo:
public class UserInfo
{
public Date birthday_at;
public String first_name;
public String last_name;
public int level;
public int gender;
}
And I want, to parse JSON string to fields of my class? How can I do this in an easiest way and in a right way? Thanx!
var obj:Object = JSON.decode( jsonString );
var user:UserInfo = new UserInfo();
for ( var prop:String in obj )
user[prop] = obj[prop];
This doesn't work for custom types with getters (read-only properties).
describeType can be used to get only the properties that can be set, but there are performance issues.
Darron Schall has a brilliant solution to take your JSON.parse(jsonString) plain object and convert it to a custom typed object.
https://github.com/darronschall/ObjectTranslator
Using the class mentioned in the previous answer, you would simply need to do the following:
var obj:Object = JSON.decode( jsonString );
var user:UserInfo = new UserInfo();
for ( var prop:String in obj )
user[prop] = obj[prop];
There is Adobe's JSON parser.
https://github.com/mikechambers/as3corelib/tree/master/
import com.adobe.serialization.json

Getting autocomplete of object-keys in flashbuilder

Is it possible to get autocomplete-functionality on objects keys?
var obj:Object = new Object();
obj.name = "AName";
obj.weight = "100";
When I type obj. -> i would like to see the keys(name,weight);
Thanks
Flash builder autocompletes only those properties/methods that are defined in the class (Defined might be a wrong word here, but I guess it is clear what I meant.) It does not autocomplete properties added in this way. As far as I know, this is not possible with flash builder.
create a class :
package {
public class NameWeightVO {
public var name : String;
public var weight : Number;
public function NameWeightVO(pName : String = "", pWeight : Number = 0) {
}
}
}
then you can create a new NameWeightVO Object with autocomplete functionality:
var nameWeightVO : NameWeightVO = new NameWeightVO();
nameWeightVO.name = "name";
nameWeightVO.weight = 10;

AS3 Custom Object to ByteArray then to Custom Object

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.
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.
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
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;
}
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);
}
}