【问题标题】:How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings?
【发布时间】:2012-10-27 19:09:55
【问题描述】:

我了解 ASP.NET Web API 本身使用 Json.NET 来(反)序列化对象,但是有没有办法指定您希望它使用的 JsonSerializerSettings 对象?

例如,如果我想在序列化的 JSON 字符串中包含type 信息怎么办?通常我会将设置注入到.Serialize() 调用中,但Web API 会默默地执行此操作。我找不到手动注入设置的方法。

【问题讨论】:

    标签: c# asp.net-web-api json.net


    【解决方案1】:

    您可以使用HttpConfiguration 对象中的Formatters.JsonFormatter.SerializerSettings 属性自定义JsonSerializerSettings

    例如,您可以在 Application_Start() 方法中执行此操作:

    protected void Application_Start()
    {
        HttpConfiguration config = GlobalConfiguration.Configuration;
        config.Formatters.JsonFormatter.SerializerSettings.Formatting =
            Newtonsoft.Json.Formatting.Indented;
    }
    

    【讨论】:

    • 我无法让它在安装了 HangFire 的 ASP.NET 应用程序中工作。它引用了不正确的库或其他东西。必须使用默认设置的其他答案..
    • 您可以按控制器或操作执行此操作:stackoverflow.com/questions/44499041/…
    【解决方案2】:

    您可以为每个JsonConvert 指定JsonSerializerSettings,并且可以设置全局默认值。

    单个 JsonConvert 带有过载:

    // Option #1.
    JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
    this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);
    
    // Option #2 (inline).
    JsonConvert.SerializeObject(YourObject, Formatting.Indented,
        new JsonSerializerSettings() {
            ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        }
    );
    

    全局设置,代码在 Global.asax.cs 中的 Application_Start()

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
         Formatting = Newtonsoft.Json.Formatting.Indented,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    };
    

    参考:https://github.com/JamesNK/Newtonsoft.Json/issues/78

    【讨论】:

    • FWIW,第二种方法是我最初尝试的方法,它不起作用。我不得不使用HttpConfiguration 代替carlosfigueira's answer,因为JsonConvert.DefaultSettings 中配置的设置没有被观察到。
    • 就我而言,全局设置 usgin JsonSerializerSettings 对我有用。我无法让 HttpCONfiguration 工作,它正在返回另一个程序集方法(Hangifre),不知道为什么。
    • 我可以使用隐藏字段formHiddenField.Value = JsonConvert.SerializeObject(listaCursos, Formatting.Indented, jsonSerializerSettings); 并使用JQuery 获取值var data = $('#formHiddenField').val(); 吗?
    【解决方案3】:

    Answer 正在将这 2 行代码添加到 Global.asax.cs Application_Start 方法中

    var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
    json.SerializerSettings.PreserveReferencesHandling = 
        Newtonsoft.Json.PreserveReferencesHandling.All;
    

    参考:Handling Circular Object References

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2012-04-05
      相关资源
      最近更新 更多