猿问

在模型绑定时将JSON中的时间戳值反序列化为DateTime

我正在使用ASP.NET Core 2开发Web API,并且具有以下Model类。


public class Model

{

   int id { get; set; }

   DateTime date { get; set; }

}

我在请求正文中使用JSON。请求Json就像


{

  "id" : 1,

  "date" : 1525261719 

}

在控制器中像这样将JSON数据绑定到Model类


[HttpPost]

public async Task<IActionResult> PostEvent([FromBody] Model model)

    // Some code here

}

我无法将Unix时间戳解析为DateTime类型。我看到了一些示例,例如JSON转换器,IModelBinder,无济于事。由于我是.NET世界的新手,所以我不知道如何解决此问题。


慕森卡
浏览 309回答 2
2回答

紫衣仙女

我遇到过同样的问题。我写了这个JsonConverter。请记住,这是针对我的具体情况量身定制的。public class UnixEpochTimeToDateTimeConverter: JsonConverter{&nbsp; &nbsp; public override bool CanWrite => false;&nbsp; &nbsp; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new NotImplementedException();&nbsp; &nbsp; }&nbsp; &nbsp; public override object ReadJson(JsonReader reader, Type objectType, object existingValue,&nbsp; &nbsp; &nbsp; &nbsp; JsonSerializer serializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (reader.TokenType == JsonToken.Null) return null;&nbsp; &nbsp; &nbsp; &nbsp; if (reader.TokenType != JsonToken.Integer) return null;&nbsp; &nbsp; &nbsp; &nbsp; if (!reader.Path.Contains("time")) return null;&nbsp; &nbsp; &nbsp; &nbsp; return long.TryParse(reader.Value.ToString(), out var epoch)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ? DateTimeOffset.FromUnixTimeMilliseconds(epoch).DateTime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; : DateTime.Now;&nbsp; &nbsp; }&nbsp; &nbsp; public override bool CanConvert(Type objectType)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return objectType == typeof(DateTime);&nbsp; &nbsp; }}

慕仙森

我找到了解决方案。我用过ITypeConverter// Converts timestamp to DateTimepublic class DateTimeConverter : ITypeConverter<long?, DateTime?>{&nbsp; &nbsp; private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);&nbsp; &nbsp; public DateTime? Convert(long? source, DateTime? destination, ResolutionContext context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!source.HasValue) return null;&nbsp; &nbsp; &nbsp; &nbsp; return _epoch.AddSeconds(source.Value);&nbsp; &nbsp; }}// Converts DateTime to Timestamppublic class TimeStampConverter : ITypeConverter<DateTime?, long?>{&nbsp; &nbsp; private readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);&nbsp; &nbsp; public long? Convert(DateTime? source, long? destination, ResolutionContext context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (source == null) return null;&nbsp; &nbsp; &nbsp; &nbsp; var result = (long)(source - _epoch).Value.TotalSeconds;&nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; }}我在startup.cs中创建了一个像这样的地图AutoMapper.Mapper.Initialize(x =>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.CreateMap<long?, DateTime?>().ConvertUsing<DateTimeConverter>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.CreateMap<DateTime?, long?>().ConvertUsing<TimeStampConverter>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });我在项目中使用了这两个类,效果很好。这可能会帮助尝试实现同一目标的任何人。
随时随地看视频慕课网APP
我要回答