JSON序列化对象与函数参数 [英] JSON serializing an object with function parameter

查看:90
本文介绍了JSON序列化对象与函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的C#对象:

var obj = new {
    username = "andrey",
    callback = "function(self) { return function() {self.doSomething()} (this) }"
}

我要JSON序列化传递到ajax调用浏览器。我用JavascriptSerializer,但序列化到以下JSON:

I need to JSON serialize it to pass to the browser in ajax call. I use JavascriptSerializer, but it serializes to the following JSON:

{"username":"andrey", "callback": "function(self) { return function() {self.doSomething()} (this) }"}

但我需要的是:

but what I need is:

{"username":"andrey", "callback": function(self) { return function() {self.doSomething()} (this) }}

  • 在各地函数定义不包括引号。
  • 现在,当JSON对象获取到浏览器,并创建了回调参数不是一个函数而是一个字符串。不知道如何解决这个问题,在服务器端preferably?

    Right now, when the JSON object gets to the browser and is created, the 'callback' parameter is not a function but a string. Any idea how to fix it, preferably on the server side?

    推荐答案

    此行​​为是经过深思熟虑的。 JSON不应该包括什么,是不是数据 - 在你的情况下执行的功能。该浏览器将开放到巨大的安全风险,如果数据可以回来的JSON格式的服务器,在执行时,就会运行任意的功能(也可以窃取信息,将用户重定向到恶意网站等。)

    This behavior is deliberate. JSON should not include anything that is not data -- in your case an executable function. The browser will be opening up to huge security risks if data can come back from a server in JSON format that, when executed, will run arbitrary functions (that can steal info, redirect the user to a malicious site etc.)

    早期JSON的实现依赖于数据恢复回来,可以通过简单的eval()执行取回对象的事实。然而,人们几乎立即意识到,这开辟了巨大的安全风险,并一直在努力,因为来处理它。这就是为什么,规范化JSON对象之前,人们停止把原始JSON数据到的eval()和使用JSON解析库代替。

    Early implementations of JSON rely on the fact that data returned back can be simply executed via eval() to get back an object. However, people almost immediately realized that this opens up huge security risks and have been trying to handle it since. That's why, before the standardized JSON object, people stopped putting raw JSON data into eval() and used JSON parsing libraries instead.

    JSON对象将始终序列化一个对象到的数据。这是由设计。标准化JSON格式已经没有办法再present可执行文件的功能。

    The JSON object will always serialize an object into data only. This is by design. THe standardized JSON format has no way to represent an executable function.

    现在,你可以很容易地将其转换回调的浏览器成为一个功能,通过它传递给eval()函数。然而,不这样做,。你只是开了自己的黑客。

    Now, you can easily convert that callback on a browser into a function by passing it through to eval(). However, don't do it. You're just opening yourself up for hacking.

    在服务器端,现代浏览器都发生设计prevent这个确切的事情 - 即数据包含可执行功能的浏览器发送

    On the server side, modern browsers are designed to prevent this exact thing from happening -- i.e. data being sent from a browser that contains an executable function.

    这篇关于JSON序列化对象与函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆