We have an ASP.NET Core 8 WEB API application which uses traditional N-layer architecture.
A repository returns a JSON array:
string jsonArray = "[
{
"id": 1,
"createDate": "2024-05-30T15:46:45"
}
]"
The model of this JSON looks like this:
public class FooBar
{
public int Id { get; set; }
public DateTime CreateDate { get; set; }
}
Having read this post, I have written the following converter:
public class DateTimeJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (typeToConvert == typeof(DateTime))
{
return DateTimeHelper.Parse(reader.GetString());
}
throw new ArgumentException("It is not a datetime");
}
public override void Write(
Utf8JsonWriter writer,
DateTime value,
JsonSerializerOptions options)
{
var utcFormat = value.Kind == DateTimeKind.Utc ? "'Z'" : string.Empty;
writer.WriterStringValue(value.ToString($"yyyy-MM-dd'T'HH:mm:ss{utcFormat}",
CultureInfo.InvariantCulture));
}
}
And I add it like this:
jsonSerializerOptions.Converters.Add(new DateTimeJsonConverter());
However, when the converter is called then the value shows the incorrect date:
I believe it should have "2024-05-30T15:46:45" value, but it shows "1/1/0001 12:00:00 AM".
Can you tell me what I am doing wrong? Am I missing something? My goal is to read JSON from the database and send it to React application. We are using System.Text.Json library.
Your JSON is in the camel case. By default, PropertyNameCaseInsensitive
is false
.
Either set PropertyNameCaseInsensitive
to true
in JsonSerializerOptions
instance
jsonSerializerOptions.PropertyNameCaseInsensitive = true;
or setting PropertyNamingPolicy
to JsonNamingPolicy.CamelCase
.
jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;