如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings? [英] How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

查看:14
本文介绍了如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I understand that ASP.NET Web API natively uses Json.NET for (de)serializing objects, but is there a way to specify a JsonSerializerSettings object that you want for it to use?

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

For example, what if I wanted to include type information into the serialized JSON string? Normally I'd inject settings into the .Serialize() call, but Web API does that silently. I can't find a way to inject settings manually.

推荐答案

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

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

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

For example, you could do that in the Application_Start() method:

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

这篇关于如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆