在 JSON.NET 中,您可以:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
System.Text.Json
是否有类似的东西?
如果没有设置默认的选项,可以手动传入吗?
另外,默认值是什么( Local
、 Utc
、 Unspecified
)?
cc @layomia关于日期
由于 DateTime 可以设置为每种格式(例如,带有和不带有时区\偏移量),读取器\写入器(以及序列化器)使用可用的内容并使用\假定 ISO 8601 格式来表示它。
@btecu序列化程序中默认使用 ISO 8601 配置文件,例如 2019-07-26T16:59:57-05:00。
对于反序列化,如果日期时间偏移量指定为“hh:mm”,则会创建带有DateTimeKind.Local
的 DateTime。 "Z" 会给DateTimeKind.Utc
。 如果没有给出偏移量,则创建一个带有DateTimeKind.Unspecified
的 DateTime。
反向映射适用于序列化:用DateTimeKind.Local
编写DateTime
将产生具有“hh:mm”格式偏移量的 ISO 表示,依此类推。
有关 System.Text.Json 中 DateTime 和 DateTimeOffset 支持的更多信息,以及如何实现自定义解析或格式设置,请参阅https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json -支持。
@btecu不幸的是,我认为在System.Text.Json
有类似选项的唯一方法是:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
并像那样实现 DateTimeConverter
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
}
}
最有用的评论
@btecu不幸的是,我认为在
System.Text.Json
有类似选项的唯一方法是:并像那样实现 DateTimeConverter