使用 Json.NET lib 通过 json 发送 javascript 函数

发布于 2024-10-15 16:47:30 字数 673 浏览 3 评论 0原文

我正在尝试通过 .Net 中的 json 发送 javascript 函数,但在序列化对象时遇到问题。

javascript 库 Highcharts 在其 json 对象上使用以下函数来自定义图表工具提示。

tooltip: {
         formatter: function() {
            var s;
            if (this.point.name) { // the pie chart
               s = ''+
                  this.point.name +': '+ this.y +' fruits';
            } else {
               s = ''+
                  this.x  +': '+ this.y;
            }
            return s;
         }
      },

我正在尝试使用流行的 Json.NET 库,使用匿名类型来创建此类对象,但我所有的努力都序列化最后到一个字符串。任何帮助表示赞赏。谢谢!

I am attempting to send a javascript function over json in .Net and I am having trouble serializing the object.

The javascript library Highcharts uses the following function on their json object to customize the chart tooltip.

tooltip: {
         formatter: function() {
            var s;
            if (this.point.name) { // the pie chart
               s = ''+
                  this.point.name +': '+ this.y +' fruits';
            } else {
               s = ''+
                  this.x  +': '+ this.y;
            }
            return s;
         }
      },

I am attempting to use the popular Json.NET library using an anonymous type to create such object but all my efforts serialize to a string in the end. Any help is appreciated. Thanks!

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

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

发布评论

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

评论(5

悍妇囚夫 2024-10-22 16:47:30

我喜欢 ObOzOne 的答案,但通过使用 WriteRawValue 可以更简单一些。例如:

public class FunctionSerializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string valueAsString = Convert.ToString(value);

        if (!string.IsNullOrWhiteSpace(valueAsString))
            writer.WriteRawValue(valueAsString);
    }
}

然后在您想要序列化的属性上:

[JsonConverter(typeof(FunctionSerializer))]
public string HideExpression { get; set; }

I like the answer from ObOzOne, but it can be a little simpler by just using the WriteRawValue. For example:

public class FunctionSerializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        string valueAsString = Convert.ToString(value);

        if (!string.IsNullOrWhiteSpace(valueAsString))
            writer.WriteRawValue(valueAsString);
    }
}

And then on your property that you want to serialize:

[JsonConverter(typeof(FunctionSerializer))]
public string HideExpression { get; set; }

天荒地未老 2024-10-22 16:47:30

JSON 顾名思义,只是一种对象表示法,适合将状态作为对象传输。

如果您需要发送 JavaScript 代码本身,可以使用 ASP NET MVC 中的 JavaScriptResult(如果您正在使用它)。

如果您使用 ASP NET Web 窗体,请拥有一个 ASPX 文件,该文件将 JavaScript 直接写入响应。确保将 ContentType 更改为 text/javascript

JSON as the name implies, is only an object notation and suitable for transferring state as object.

If you need to send JavaScript code itself, you can use a JavaScriptResult in ASP NET MVC if you are using it.

If you are using ASP NET Web Forms, have an ASPX file which writes the JavaScript straight to the response. Make sure you change the ContentType to text/javascript.

初熏 2024-10-22 16:47:30

从 Newtonsoft.Json 12.0.1 (11/27/2018) 开始,标准解决方案是使用 Jraw 类型。

public class JavaScriptSettings
{
    public JRaw OnLoadFunction { get; set; }
    public JRaw OnUnloadFunction { get; set; }
}

JavaScriptSettings settings = new JavaScriptSettings
{
    OnLoadFunction = new JRaw("OnLoad"),
    OnUnloadFunction = new JRaw("function(e) { alert(e); }")
};

string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

Console.WriteLine(json);
// {
//   "OnLoadFunction": OnLoad,
//   "OnUnloadFunction": function(e) { alert(e); }
// }

来源

As of Newtonsoft.Json 12.0.1 (11/27/2018), the standard solution for this is to use JRaw type.

public class JavaScriptSettings
{
    public JRaw OnLoadFunction { get; set; }
    public JRaw OnUnloadFunction { get; set; }
}

JavaScriptSettings settings = new JavaScriptSettings
{
    OnLoadFunction = new JRaw("OnLoad"),
    OnUnloadFunction = new JRaw("function(e) { alert(e); }")
};

string json = JsonConvert.SerializeObject(settings, Formatting.Indented);

Console.WriteLine(json);
// {
//   "OnLoadFunction": OnLoad,
//   "OnUnloadFunction": function(e) { alert(e); }
// }

Source

淤浪 2024-10-22 16:47:30

有点黑客,但我这样解决了它:

string linkUrl = "http://www.google.com";
dynamic result = new ExpandoObject();
result.render = "FUNCfunction (data) { return '<a href=\"" + linkUrl + "\">' + data + '</a>'; }FUNC";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(result).Replace("\"FUNC", "").Replace("FUNC\"", "")

通过用 FUNC 占位符包围我的函数,然后用生成的 json 中的空字符串替换“FUNC 和 FUNC”,我在 json 对象中得到了该函数。

A bit of a hack but I solved it this way:

string linkUrl = "http://www.google.com";
dynamic result = new ExpandoObject();
result.render = "FUNCfunction (data) { return '<a href=\"" + linkUrl + "\">' + data + '</a>'; }FUNC";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(result).Replace("\"FUNC", "").Replace("FUNC\"", "")

By surrounding my function with the FUNC placeholders and then replacing "FUNC and FUNC" with emtpy string in the generated json I get the function in my json object.

﹎☆浅夏丿初晴 2024-10-22 16:47:30

我受到上面示例中通用方法的启发:

public class FunctionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(String));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, String.Concat("<Function>", value, "</Function>"));
    }
}

public static class JsonObjectExtensions
{
    public static String CleanJson(this String s)
    {
        return s.Replace("\"<Function>", "").Replace("</Function>\"", "");
    }
}

public partial class JsonObject
{
    public String ToJson()
    {
        return JsonConvert.SerializeObject(this).CleanJson();
    }
}

以及模型数据:

public class ConfigModel : JsonObject
{
    [JsonProperty("altFormat", NullValueHandling = NullValueHandling.Ignore)]
    public String altFormat { get; set; }

    [JsonProperty("onClose", NullValueHandling = NullValueHandling.Ignore)]
    [JsonConverter(typeof(FunctionConverter))]
    public String onClose { get; set; }

}

I was inspired by the example above by generic methods :

public class FunctionConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(String));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, String.Concat("<Function>", value, "</Function>"));
    }
}

public static class JsonObjectExtensions
{
    public static String CleanJson(this String s)
    {
        return s.Replace("\"<Function>", "").Replace("</Function>\"", "");
    }
}

public partial class JsonObject
{
    public String ToJson()
    {
        return JsonConvert.SerializeObject(this).CleanJson();
    }
}

And the model data :

public class ConfigModel : JsonObject
{
    [JsonProperty("altFormat", NullValueHandling = NullValueHandling.Ignore)]
    public String altFormat { get; set; }

    [JsonProperty("onClose", NullValueHandling = NullValueHandling.Ignore)]
    [JsonConverter(typeof(FunctionConverter))]
    public String onClose { get; set; }

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