我有这个 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 对象到达浏览器并被创建时,“回调”参数不是一个函数而是一个字符串。知道如何修复它,最好是在服务器端吗?
最佳答案
我正在尝试完成类似的事情。
在我的例子中,我使用 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 对象。
发布: How to serialize a function to json (using razor @<text>)
关于c# - JSON使用函数参数序列化一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5373540/