How do you serialize javascript objects with methods using JSON?

一个人想着一个人 提交于 2019-11-29 16:31:15
Staale

I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.

I do believe though that "f = "+function() {} will yield you a to string version that you can eval:

var test = "f = " + function() { alert("Hello"); };
eval(test)

And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.

Try to get away without serializing javascript code. That way lies a world of pain. Debugging will be much easier if code can only come from static files, not from a database. Instead, walk your JSON responses after you receive them and pass the appropriate data to the appropriate object constructors.

If you absolutely must serialize them, calling toString() on a function will return its source.

If you use WCF framework to develop RESTful web service, that is very easy to achieve. Simply create your data structure classes with your desired collection with DataContract, DataMember attributes.

[DataContract]
public class Foo
{
    [DataMember]
     public string FooName {get;set;}
    [DataMember]
     public FooItem[] FooItems {get;set;}
}


[DataContract]
public class FooItem
{
    [DataMember]
    public string Name {get;set;}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!