为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕森卡 2021-05-13 21:22:53
我正在使用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世界的新手,所以我不知道如何解决此问题。
查看完整描述

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);

    }

}


查看完整回答
反对 回复 2021-05-23
?
慕仙森

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>();

            });

我在项目中使用了这两个类,效果很好。这可能会帮助尝试实现同一目标的任何人。


查看完整回答
反对 回复 2021-05-23
  • 2 回答
  • 0 关注
  • 279 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信