有没有办法为Json.net指定全局设置?
我们遇到的问题是它将所有DateTimes都置于UTC(正确地说是这样)。出于传统目的,我们希望默认为本地时间。我不想在下面放置以下代码:
var settings = New JsonSerializerSettings();
settings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
JsonConvert.DeserializeObject(json, settings);
答案 0 :(得分:22)
所以,这被添加到Json.net 5.0 Release 5
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
答案 1 :(得分:5)
是的,确实你可以像Lodewijk解释的那样设置默认的Json.Net设置。但是Web API使用它自己的设置,你必须单独设置它们。
services.AddMvc(opts =>
{
var jsonFormatter = (JsonOutputFormatter) opts.OutputFormatters
.First(formatter => formatter is JsonOutputFormatter);
jsonFormatter.PublicSerializerSettings.Converters.Add(new StringEnumConverter());
});
var config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Converters
.Add(new StringEnumConverter());
此外,Json.NET现在有一个API来设置默认的全局设置:
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
return settings;
};