【问题标题】:Deserializing JSON to DateTime property throws exception将 JSON 反序列化为 DateTime 属性会引发异常
【发布时间】:2020-03-18 14:36:07
【问题描述】:

我正在尝试反序列化以下 JSON:

{
    "Anriss": "SomeAnriss",
    "ArtikelId": 123123,
    "Image": null,
    "KanalId": 101,
    "MediumName": "SomeMediumName",
    "PublikationsDatum": "/Date(1573581177000)/",
    "Titel": "SomeTitel",
    "Link": null
}

通过这个方法调用:

await this.jsonHelper.DeserializeJsonContent<AvenueArtikelDetail>(httpResponseMessage.Content);

方法:

public async Task<T> DeserializeJsonContent<T>(HttpContent responseContent)
{
    var content = await responseContent.ReadAsStringAsync();
    var deserializedJsonContent = JsonSerializer.Deserialize<T>(content, new JsonSerializerOptions {PropertyNameCaseInsensitive = true, IgnoreNullValues = true});
    return deserializedJsonContent;
}

很遗憾,我收到以下错误:

System.Text.Json.JsonException: '无法将 JSON 值转换为 System.DateTime。路径:$.PublikationsDatum |行号:0 | BytePositionInLine:353。'

JSON 来自对此 API 方法的调用:

[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetArtikelDetail(ArtikelDetailSearchDto searchDto)
{
    var artikelDetail = this.artikelDetailService.GetArtikelDetailBy(searchDto);
    return this.Json(artikelDetail, JsonRequestBehavior.AllowGet);
}

publikationsDatum 是一个普通的DateTime 属性

public DateTime PublikationsDatum { get; set; }

我做错了什么?如何将 JSON 的 publikationsDatum 反序列化回 DateTime?

提前致谢

编辑:我们没有使用任何 JSON 库,并希望保持这种方式。我们正在使用System.Text.Json

【问题讨论】:

标签: c# .net json asp.net-core-3.0 system.text.json


【解决方案1】:

/Date( and )/ 中的数字是自 UNIX 纪元以来的毫秒数。

您可以像这样制作自定义转换器:

public class DateTimeConverter : JsonConverter<DateTime>
{

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // You should do some fool proof parsing here
        var s = reader.GetString();
        s=s.Replace("/Date(","").Replace(")/","");
        long epoch = Convert.ToInt64(s);
        DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(epoch);
        return dateTimeOffset.UtcDateTime;
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        // Do some conversion here
    }
}

这是一个 .net 小提琴: https://dotnetfiddle.net/tAK62c

【讨论】:

  • 谢谢你的作品!我喜欢这比序列化为字符串并让另一个属性解析字符串要好得多:)
  • 如果纪元在毫秒精度以下,您将失去它。如果没有一辆汽车以防万一,这没什么大不了的。
猜你喜欢
  • 2019-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
相关资源
最近更新 更多