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

查看:59
本文介绍了如何在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.

推荐答案

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

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天全站免登陆