问题描述
有没有办法为 Json.net 指定全局设置?
Is there a way to specify global settings for Json.net?
我们遇到的问题是它将所有 DateTimes 都放在 UTC 中(这是正确的).出于遗留目的,我们希望默认为当地时间.我不想到处乱写下面的代码:
The problem we're having is that it puts all DateTimes in UTC (rightly so). For legacy purposes, we want to default to Local time. I don't want to put the following code all over the place:
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
};
来自 发行说明:
使用 JsonConvert.DefaultSettings
设置一次a> 在应用程序中,所有对 JsonConvert.SerializeObject
/DeserializeObject
和 JToken.ToObject
/<的调用都会自动使用默认设置代码>从对象代码>.任何用户为这些调用提供的设置都将覆盖默认设置.
Set once with
JsonConvert.DefaultSettings
in an application, the default settings will automatically be used by all calls toJsonConvert.SerializeObject
/DeserializeObject
, andJToken.ToObject
/FromObject
. Any user supplied settings to these calls will override the default settings.
因为在某些情况下不应自定义 JSON,例如Facebook 或 Twitter 库,默认情况下 JsonSerializer
不会使用 DefaultSettings
,为那些框架或应用程序中不应使用默认设置的位置提供选择退出.要创建一个确实使用它们的 JsonSerializer
,有一个新的 JsonSerializer.CreateDefault()
方法.
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 时,例如在模型绑定或响应格式中,它选择不使用这些全局默认设置.要配置 ASP.NET 内部使用的默认值,请参阅 this answer by 安德烈.
Do note that when ASP.NET invokes Newtonsoft directly, e.g. in model binding or response formatting, it opts out of using these global default settings. To configure defaults used internally by ASP.NET see this answer by Andrei.
这篇关于Json.net 全局设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!