1

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

13

1 Answer 1

1

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

2
  • thank you this works! I like that alot better than serializing to a string and having another property parse the string :)
    – xeraphim
    Nov 22, 2019 at 15:08
  • If the epoch is under the millisecond precision, you will loose it. Not a big deal if not one cars ubt just in case. Nov 22, 2019 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.