gpt4 book ai didi

c# - JsonConverter 不作为属性属性

转载 作者:行者123 更新时间:2023-11-30 18:45:30 28 4
gpt4 key购买 nike

我有一个对象,其中包含一个具有 JsonConverter 属性的属性。对于数据读写,转换器不工作。声明的属性是

[JsonConverter(typeof(EpochDateTimeConverter))]
public DateTime CreatedOn { get; set; }

EpochDateTimeConverter 是

public class EpochDateTimeConverter : DateTimeConverterBase
{
private static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}

long millisecondsSinceEpoch;
if (value is DateTime)
{
millisecondsSinceEpoch = Convert.ToInt64((((DateTime)value).ToUniversalTime() - epoch).TotalMilliseconds);
}
else
{
if (!(value is DateTimeOffset))
throw new JsonSerializationException("Expected date object value.");
millisecondsSinceEpoch = Convert.ToInt64((((DateTimeOffset)value).ToUniversalTime().UtcDateTime - epoch).TotalMilliseconds);
}
writer.WriteValue(millisecondsSinceEpoch);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (objectType != typeof(DateTime?) && objectType != typeof(DateTimeOffset?))
throw new JsonSerializationException($"Cannot convert null value to {objectType}");

return null;
}
if (reader.TokenType == JsonToken.Integer || reader.TokenType == JsonToken.Float)
{
var millisecondsSinceEpoch = (long)reader.Value;
var dateTime = FromUnixTime(millisecondsSinceEpoch);
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
{
return dateTime;
}
else
{
return new DateTimeOffset(dateTime);
}
}
if (reader.TokenType == JsonToken.Date || reader.TokenType == JsonToken.Float)
{
return ConvertToUnixTimestamp(Convert.ToDateTime(reader.Value));
}
throw new JsonSerializationException($"Cannot convert to DateTime or DateTimeOffset from token type {reader.TokenType}");
}
private static DateTime FromUnixTime(long unixTime)
{
try
{
return epoch.AddSeconds(unixTime);
}
catch(Exception)
{
unixTime = unixTime / 1000;
return epoch.AddSeconds(unixTime);
}

}

public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}

}

我无法得到错误。但是 EpochDateTimeConverter 不会自动调用。我不明白出了什么问题。谁能帮帮我?

最佳答案

确保使用 System.Text.Json.Serialization 而不是 Newtonsoft.Json

关于c# - JsonConverter 不作为属性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49248429/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com