有没有办法为 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 toJsonConvert.SerializeObject
/DeserializeObject
, andJToken.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 useDefaultSettings
, providing an opt-out for those frameworks or for places in your application that shouldn’t use default settings. To create aJsonSerializer
that does use them there is a newJsonSerializer.CreateDefault()
method.
请注意,当 ASP.NET 直接调用 Newtonsoft 时,例如在模型绑定(bind)或响应格式中,它选择不使用这些全局默认设置。要配置 ASP.NET 内部使用的默认值,请参阅 this answer通过 Andrei .
关于c# - Json.net 全局设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066904/