开发者

Best way to typecast deserialised JSON

I think I've established that in as3corelib JSON.decode I have no choice but to deserialise to a plain old flex object.

var data:Object = JSON.decode(json);

If I then want to get the data contained in the object into another type I can't use type casting. I have to instantiate a new instance and add the properties manually.

var data:Object = JSON.decode(json);
var model:Model = new Model();
model.name = data.name;
model.notes = data.notes;

A pain and a bit ugly, but I'm guessing this is the price to be paid for going from untyped json to a flex type. My first question is whether my assumption is correct and there is no prettier way to create my model instance with the data contained within the json?

My second question, if so then before I write my own method to do this, is there anything inside the flex api that will take the data object and mixin it's values to my model in开发者_如何学运维stance?

Cheers,

Chris


the approach I've always used proved to be part of the AMF3 serialization mechanism in ActionScript.

have a look at IExternalizable and registerClassAlias.

now what I use is the following:

interface ISerializable {
    public function getRawData():Object;
    public function setRawData(param:Object):void;
}
function registerType(id:String, type:Class):void {
    //implementation
}
function getTypeByID(id:String):Class {
    //implementation
}
function getTypeID(type:Class):String {
    //implementation
}

and to the decoder/encoder you register a class alias.

serialization of an object works as follows:

var raw:Object = model.getRawData();
raw[" type"] = getTypeID(model);
var encoded:String = JSON.encode(raw);

decoding works as follows:

var raw:Object = JSON.decode(raw);
var cl:Class = getTypeByID(raw[" type"]);
if (cl == null) throw new Error("no class registered for type: "+raw[" type"]);
delete raw[" type"];
var model:ISerializable = new cl();
model.setRawData(raw);

you will need to do this recursively on the whole deserialized JSON tree, starting at the leafs. For cyclic reference, you'll need a trick. I had an implementation of this somewhere, but I can't find it.


You can loop within the field of you json decoded object and assign them into your model:

function json2model(json:String):Model{
 var data:Object = JSON.decode(json);

 var m:Model=new Model();

 for (var field:String in data) {
  if (m.hasOwnProperty(field)) {
   m[field] = data[field];
  }
 }

 return m;
} 

var model:Model=json2model(json)

or add a static function within your Model if you preffer:

public class Model {
 //...
 public static function fromJSon(json:String):Model {
     var data:Object = JSON.decode(json);

     var m:Model=new Model();

     for (var field:String in data) {
      if (m.hasOwnProperty(field)) {
       m[field] = data[field];
      }
     }

     return m;
    } 
 }
}

var model:Model=Model.fromJSon(json);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜