I'm creating a Asp.Net Core 3.1 Web Api. I have a need to serialize date without time in a Get method. I read that Asp.Net 3.1 uses System.Text.Json for serialization by default. So, I Added JsonConverter attribute to model property and added a Converter. The Converter class using System.Text.Json does not work but the one using Json.Net work (See below code). Do I need to add anything for Converter in System.Text.Json to work?
[JsonConverter(typeof(DateConverter))]
public DateTime date { get; set; }
System.Text.Json
public class DateConverter : JsonConverter<DateTime>
{
public override DateTime Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
DateTime.ParseExact(reader.GetString(),
"yyyy-MM-dd", CultureInfo.InvariantCulture);
public override void Write(
Utf8JsonWriter writer,
DateTime dateTimeValue,
JsonSerializerOptions options) =>
writer.WriteStringValue(dateTimeValue.ToString(
"yyyy-MM-dd", CultureInfo.InvariantCulture));
}
Json.Net
Register in Startup.cs
services.AddControllers()
.AddNewtonsoftJson();
public class DateConverter : IsoDateTimeConverter
{
public DateConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}