开发者

Casting JSON Results In Script#

I'm trying to do something l开发者_开发技巧ike the following in Script#

jQuery.GetJson("./GetData/", delegate(object json)
{
    //json = {"Name":"Fred"}    
    Person p = (Person)json;
    Script.Alert(p.Name);
});

Obviously the direct cast doesn't work because the a cleint side Person object actually uses set_Name and the Name property is private. I can't seem to find anything built into Script# to support this, am I just missing it or am I going to have to do it myself?


I see this is already answered. You need to explicitly cast the object, if anyone's coming by and scratching their head this is how you do it:

    [Imported]
    [IgnoreNamespace]
    public class Person
    {
        public string fullname;
        public string address;

        public static implicit operator Person(Dictionary o) { return null; }
    }

Then in your GetJson:

jQuery.GetJson("GetData", delegate(object sender) {
    Person p = Dictionary.GetDictionary(sender);  
}); 


Your best option for customizing deserialization is a hand-written constructor or a factory method. This is pretty true in any environment – if you're underlying type isn't one-to-one compatible with the serialization, you're going to need to be more specific.

We've been using Script# for a large project, and this has generally been our approach when confronted with these situations. That said, we usually try to write our own types using properties, so that deserialization works more naturally.

Is it safe to assume that, for some reason, you don't have control of the Person class definition? If that's not the case, I would highly recommend you refactor the class to use a "Name" property with a private "name" backing field. Not only is this more idiomatic, it might also save you some hassle.

Edit:

Wrote with my brain off. Do forgive. I should have said that we try to write a script-side classes using fields rather than properties. Then again, our needs from server to client are so different that we don't even try to use the same library on both sides, so we can get away with that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜