2 回答
TA贡献1839条经验 获得超15个赞
我遇到过同样的问题。我写了这个JsonConverter。请记住,这是针对我的具体情况量身定制的。
public class UnixEpochTimeToDateTimeConverter: JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
if (reader.TokenType != JsonToken.Integer) return null;
if (!reader.Path.Contains("time")) return null;
return long.TryParse(reader.Value.ToString(), out var epoch)
? DateTimeOffset.FromUnixTimeMilliseconds(epoch).DateTime
: DateTime.Now;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}
TA贡献1827条经验 获得超7个赞
我找到了解决方案。我用过ITypeConverter
// Converts timestamp to DateTime
public class DateTimeConverter : ITypeConverter<long?, DateTime?>
{
private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public DateTime? Convert(long? source, DateTime? destination, ResolutionContext context)
{
if (!source.HasValue) return null;
return _epoch.AddSeconds(source.Value);
}
}
// Converts DateTime to Timestamp
public class TimeStampConverter : ITypeConverter<DateTime?, long?>
{
private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public long? Convert(DateTime? source, long? destination, ResolutionContext context)
{
if (source == null) return null;
var result = (long)(source - _epoch).Value.TotalSeconds;
return result;
}
}
我在startup.cs中创建了一个像这样的地图
AutoMapper.Mapper.Initialize(x =>
{
x.CreateMap<long?, DateTime?>().ConvertUsing<DateTimeConverter>();
x.CreateMap<DateTime?, long?>().ConvertUsing<TimeStampConverter>();
});
我在项目中使用了这两个类,效果很好。这可能会帮助尝试实现同一目标的任何人。
- 2 回答
- 0 关注
- 308 浏览
添加回答
举报