C
C#5mo ago
Tostisto

Problem with json deserialization

I have an issue with deserialization of the datetime from a JSON string. I need to deserialize 2024-07-09T10:36:23:000Z into a datetime object, but currently, I am having a problem with deserialization. My code looks like this:
using System;
using System.Text.Json;

string jsonString = "{\"Date\":\"2024-07-09T10:36:23:000Z\",\"Message\":\"Hello, World!\"}";

MyData? data = JsonSerializer.Deserialize<MyData>(jsonString);

Console.WriteLine(data.Date); // Output: 7/9/2024 10:36:23 AM

public class MyData
{
public DateTime Date { get; set; }
public string Message { get; set; }
}
using System;
using System.Text.Json;

string jsonString = "{\"Date\":\"2024-07-09T10:36:23:000Z\",\"Message\":\"Hello, World!\"}";

MyData? data = JsonSerializer.Deserialize<MyData>(jsonString);

Console.WriteLine(data.Date); // Output: 7/9/2024 10:36:23 AM

public class MyData
{
public DateTime Date { get; set; }
public string Message { get; set; }
}
With this error
System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $.Date | LineNumber: 0 | BytePositionInLine: 34.
---> System.FormatException: The JSON value is not in a supported DateTime format.
System.Text.Json.JsonException: The JSON value could not be converted to System.DateTime. Path: $.Date | LineNumber: 0 | BytePositionInLine: 34.
---> System.FormatException: The JSON value is not in a supported DateTime format.
Shoud be problem in culture setting in os? Or how can I serialize it without creating a new converter?
2 Replies
Pobiega
Pobiega5mo ago
the problem is your datetime string 2024-07-09T10:36:23:000Z is not ISO 8601-1:2019 you can add your own custom converter to handle this format, if you are locked into that format
Angius
Angius5mo ago
Yeah, miliseconds are separated with a . in ISO 8601 Ideally, you'd change whatever returns that data to use proper ISO format Failing that, as Pobiega said, custom converter
Want results from more Discord servers?
Add your server