使用函数参数序列化对象的 JSON

发布于 2024-10-23 19:19:19 字数 623 浏览 2 评论 0原文

我有这个 C# 对象:

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

我需要 JSON 序列化它以在 ajax 调用中传递给浏览器。我使用 JavascriptSerializer,但它序列化为以下 JSON:

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

但我需要的是:

{"username":"andrey", "callback": function(self) { return function() {self.doSomething()} (this) }}
  • 函数定义周围没有引号。

现在,当 JSON 对象到达浏览器并被创建时,“callback”参数不是函数而是字符串。知道如何修复它,最好是在服务器端吗?

I have this C# object:

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

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) }}
  • no quotes around function definition.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故事还在继续 2024-10-30 19:19:19

我试图完成类似的事情。
就我而言,我使用 MVC Razor 语法尝试生成一个 json 对象,其中包含使用 @传入的函数。句法。

我能够使用 Json.net 库(使用 JsonConvert 和 Jraw)获得所需的输出。

示例:

// set the property value using JRaw
var obj = new {
    username = "andrey",
    callback = new JRaw("function(self) { return function() {self.doSomething()} (this) }")
}
// and then serialize using the JsonConvert class
var jsonObj = JsonConvert.SerializeObject(obj);

这应该会为您提供带有函数的 json 对象(而不是字符串中的函数)。

邮政:
如何将函数序列化为 json(使用 razor @< ;文本>)

I was trying to accomplish something similar.
In my case I was using MVC Razor syntax trying to generate a json object with a function passed in using the @<text> syntax.

I was able to get the desired output using the Json.net library (using JsonConvert and JRaw).

Example:

// set the property value using JRaw
var obj = new {
    username = "andrey",
    callback = new JRaw("function(self) { return function() {self.doSomething()} (this) }")
}
// and then serialize using the JsonConvert class
var jsonObj = JsonConvert.SerializeObject(obj);

That should get you the json object with the function (instead of the function in a string).

Post:
How to serialize a function to json (using razor @<text>)

蛮可爱 2024-10-30 19:19:19

这种行为是故意的。 JSON 不应包含任何非数据的内容——在您的情况下是可执行函数。 格式从服务器返回,并且在执行时将运行任意函数(可以窃取信息、将用户重定向到恶意站点等),那么浏览器将面临巨大的安全风险。

如果数据可以JSON 依赖于这样一个事实,即可以通过 eval() 简单地执行返回的数据来获取对象。然而,人们几乎立即意识到这会带来巨大的安全风险,并从那时起就一直在努力解决它。这就是为什么在标准化 JSON 对象之前,人们不再将原始 JSON 数据放入 eval() 中,而是使用 JSON 解析库。

JSON 对象始终将对象序列化为数据。这是设计使然。标准化的 JSON 格式无法表示可执行函数。

现在,您可以通过将浏览器上的回调传递给 eval() 轻松地将其转换为函数。但是,不要这样做。你只是让自己容易受到黑客攻击。

在服务器端,现代浏览器旨在防止这种情况发生——即从包含可执行函数的浏览器发送的数据。

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

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.

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.

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.

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.

赤濁 2024-10-30 19:19:19

您可以使用 Function 对象的构造函数。请参阅 https://developer.mozilla.org/nl/docs /Web/JavaScript/Reference/Global_Objects/Function

在 json 中,您将回调属性设置为描述 Function 构造函数参数的字符串数组。然后,当 json 数据到达客户端时,您必须将数组转换为 Function 对象的实例。

这样,您就可以在后台数据库中获得函数实现详细信息,而不是在源代码中进行硬编码。

const json = '{"username":"andrey","callback":["self","return self.doSomething()"]}';

//Parse the json to an object
const object = JSON.parse(json);

//Convert the callback property from Array to Function
object["callback"] = new Function(...object["callback"]);

//Create a parameter for calling the Function
var self = {
    doSomething() {
        console.log("Do something called");
    }
}

//Call the function
object["callback"](self);

You can make use of the constructor of the Function object. See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Function.

In your json you set the callback property to a string array that describes the Function constructor parameters. Then when the json data has arrived on the client you have to convert the Array to an instance of the Function object.

This way you can have the function implementation details in your back database instead of hardcoded in source code.

const json = '{"username":"andrey","callback":["self","return self.doSomething()"]}';

//Parse the json to an object
const object = JSON.parse(json);

//Convert the callback property from Array to Function
object["callback"] = new Function(...object["callback"]);

//Create a parameter for calling the Function
var self = {
    doSomething() {
        console.log("Do something called");
    }
}

//Call the function
object["callback"](self);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文