xeraphim
xeraphim

Reputation: 4645

Deserializing JSON to DateTime property throws exception

I'm trying to deserialize the following JSON:

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

via this method call:

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

Method:

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

Unfortunately, I get the following error:

System.Text.Json.JsonException: 'The JSON value could not be converted to System.DateTime. Path: $.PublikationsDatum | LineNumber: 0 | BytePositionInLine: 353.'

The JSON comes from a call to this API method:

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

The publikationsDatum is a normal DateTime property

public DateTime PublikationsDatum { get; set; }

What am I doing wrong? How can I deserialize the publikationsDatum of the JSON back to a DateTime?

Thanks in advance

Edit: We're not using any JSON library and would like to keep it that way. We're using System.Text.Json

Upvotes: 1

Views: 967

Answers (1)

Palle Due
Palle Due

Reputation: 6312

The number within /Date( and )/ is the milliseconds since the UNIX epoch.

You can make a custom converter like this:

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
    }
}

Here is a .net fiddle: https://dotnetfiddle.net/tAK62c

Upvotes: 2

Related Questions