0

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";
    }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
frosty
  • 2,421
  • 6
  • 26
  • 47
  • When I use your `System.Text.Json` method to test, everything works fine and the date returned in json is in the form of "yyyy-MM-dd" .Please make sure you are using `System.Text.Json.JsonSerializer` to serialize date: `string json = System.Text.Json.JsonSerializer.Serialize(testDate);` – LouraQ Jun 08 '20 at 08:55
  • Note that in case of Json.Net, I don't need to explicitly serialize to return the model from Asp.Net Controller method. I just return the model from the controller method and serialization happens in Asp.Net core stack. My controller method signature: public async Task>> MyControllerGetMethod() – frosty Jun 08 '20 at 15:54

0 Answers0