c# - Json.net 全局设置

标签 c# json.net

有没有办法为 Json.net 指定全局设置?

我们遇到的问题是它将所有 DateTimes 都放在 UTC 中(这是正确的)。出于遗留目的,我们希望默认为本地时间。我不想将以下代码放在各处:

var settings = New JsonSerializerSettings();
settings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
JsonConvert.DeserializeObject(json, settings);

最佳答案

所以,这被添加到 Json.net 5.0 Release 5

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    DateTimeZoneHandling = DateTimeZoneHandling.Local
};

来自release notes :

Set once with JsonConvert.DefaultSettings in an application, the default settings will automatically be used by all calls to JsonConvert.SerializeObject/DeserializeObject, and JToken.ToObject/FromObject. Any user supplied settings to these calls will override the default settings.

Because there are cases where JSON should not be customized, e.g. a Facebook or Twitter library, by default JsonSerializer won’t use DefaultSettings, providing an opt-out for those frameworks or for places in your application that shouldn’t use default settings. To create a JsonSerializer that does use them there is a new JsonSerializer.CreateDefault() method.

请注意,当 ASP.NET 直接调用 Newtonsoft 时,例如在模型绑定(bind)或响应格式中,它选择不使用这些全局默认设置。要配置 ASP.NET 内部使用的默认值,请参阅 this answer通过 Andrei .

关于c# - Json.net 全局设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066904/

相关文章:

c# - 将 HttpClient 和 HttpWebRequest 用于 Https TLS1.2

c# - 带有日期字段的 JSON 模式验证

c# - 保留删除 Newtonsoft.Json 中的尾随零

c# - 创建一个事件来观察变量的变化

C# 按类型解析 JSON 组

c# - 在 Web API 中将包含 JToken 的对象序列化为 XML 时出现循环引用异常

c# - 为什么 JsonConvert 在反序列化为字典时抛出异常

C# 相对路径不从工作目录开始

c# - 什么是 C# 中的内部密封类?

c# - 减少 ASP.NET MVC 应用程序初始启动时的 JIT 开销