using NCC.Dependency;
using NCC.Extensions;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NCC.JsonSerialization
{
///
/// DateTimeOffset 类型序列化
///
[SuppressSniffer]
public class DateTimeOffsetJsonConverter : JsonConverter
{
///
/// 默认构造函数
///
public DateTimeOffsetJsonConverter()
{
Format ??= "yyyy-MM-dd HH:mm:ss";
}
///
/// 构造函数
///
///
public DateTimeOffsetJsonConverter(string format)
{
Format = format;
}
///
/// 构造函数
///
///
///
public DateTimeOffsetJsonConverter(string format, bool outputToLocalDateTime)
{
Format = format;
OutputToLocalDateTime = outputToLocalDateTime;
}
///
/// 时间格式化格式
///
public string Format { get; private set; }
///
/// 是否输出为为当地时间
///
public bool OutputToLocalDateTime { get; set; } = false;
///
/// 反序列化
///
///
///
///
///
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTimeOffset.Parse(reader.GetString());
}
///
/// 序列化
///
///
///
///
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
// 判断是否序列化成当地时间
var formatDateTime = OutputToLocalDateTime ? value.ConvertToDateTime() : value;
writer.WriteStringValue(formatDateTime.ToString(Format));
}
}
}