BoeykensBrooklyn
BoeykensBrooklyn

Reputation: 85

C# Datetime cannot convert yyyy-MM-dd'T'HH:mm:ss.SSSZ to Datetime

For a project I am creating an ASP.net Core Web API.

I created a POST endpoint for request from a Webhook (Java API)

My C# Class:

public class Data
{
    [JsonPropertyName("state")]
    public string? state { get; set; }

    [JsonPropertyName("lat")]
    public double? lat { get; set; }

    [JsonPropertyName("lng")] 
    public double? lng { get; set; }

    [JsonPropertyName("accuracy")]
    public int? accuracy { get; set; }

    [JsonPropertyName("source")]
    public string? source { get; set; }

    [JsonPropertyName("id")]
    public int? id { get; set; }

    [JsonPropertyName("time")]
    public DateTime? time { get; set; }

    [JsonPropertyName("insertTime")]
    public DateTime? insertTime { get; set; }

    [JsonPropertyName("serial")]
    public string? serial { get; set; }
}

So I thought datetime could dealing with following format: 2023-03-01T15:25:00+0000 But I always get an error from this type:

"The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path: $.data.time | LineNumber: 0 | BytePositionInLine: 139."

Someone that have a solution?

Thanks in Advance.

UPDATE:

JSON :

{
   "dataType":"location",
   "data": {
       "state":"STOP",
       "lat":50.00,
       "lng":5.00,
       "source":"gps",
       "id":1804885154,
       "time":"2023-03-01T11:12:00+0000",
       "insertTime":"2023-03-01T11:18:30+0000",
       "serial":"xxxx"
    }
}

FULL C# CLASS:

public class SensolusSensorWebhook
{
    [JsonProperty("dataType")]
    public string? DataType { get; set; }

    [JsonProperty("data")]
    public Data? Data { get; set; }
}

public class Data
{
    [JsonPropertyName("state")]
    public string? state { get; set; }

    [JsonPropertyName("lat")]
    public double? lat { get; set; }

    [JsonPropertyName("lng")]
    public double? lng { get; set; }

    [JsonPropertyName("accuracy")]
    public int? accuracy { get; set; }

    [JsonPropertyName("source")]
    public string? source { get; set; }

    [JsonPropertyName("id")]
    public int? id { get; set; }

    [JsonPropertyName("time")]
    public DateTime? time { get; set; }

    [JsonPropertyName("insertTime")]
    public DateTime? insertTime { get; set; }

    [JsonPropertyName("serial")]
    public string? serial { get; set; }

    [JsonPropertyName("thirdPartyId")]
    public string? thirdPartyId { get; set; }
}

Swagger UI Info: Foto van endpoint in swagger

Endpoint code:

[HttpPost("sensordata/sensolus")]  
public async Task<ActionResult> PostSensolusWebhook([FromBody] SensolusSensorWebhook? sensorWebhook)
{
    _logger.LogInformation("Falls in PostSensolusWebhook");
    _logger.LogInformation($"Sensorwebhook: {sensorWebhook.ToString()}");
    await _sensorTestDataService.CreateAsync(sensorWebhook);

        
    return Ok(sensorWebhook);
}

Upvotes: 3

Views: 1155

Answers (1)

Mad hatter
Mad hatter

Reputation: 916

You should use a converter for this case.

var json = File.ReadAllText("data.json");
var options = new JsonSerializerOptions();
var converter = new DateTimeConverterUsingDateTimeParse();

options.Converters.Add(converter);

var data = JsonSerializer.Deserialize<Data>(json, options);

Here is the converter class

public class DateTimeConverterUsingDateTimeParse : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));
        return DateTime.Parse(reader.GetString() ?? string.Empty, CultureInfo.InvariantCulture);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture));
    }
}

This code was taken from here

You can add your custom converter to your web server while configuring your services.

services.AddControllers()
        .AddJsonOptions(options =>
        {
             options.JsonSerializerOptions.Converters.Add(new DateTimeConverterUsingDateTimeParse());
        });

Upvotes: 3

Related Questions