gpt4 book ai didi

c# - JSON使用函数参数序列化一个对象

转载 作者:可可西里 更新时间:2023-11-01 08:03:35 25 4
gpt4 key购买 nike

我有这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com