NSwag - using date format for string property in auto-generated DTOs

Viewed 45

I am using NSwag to generate DTOs. In the yaml I specify a property with a date format as follows:

 User:
    type: object
    additionalProperties: false
    properties:
    createdAt:
        type: string
        format: date

This generates the C#:

    [System.Text.Json.Serialization.JsonPropertyName("createdAt")]
    [System.Text.Json.Serialization.JsonConverter(typeof(DateFormatConverter))]
    public System.DateTimeOffset CreatedAt { get; set; } = default!;

Which uses the newly generated class of DateFormatConverter:

[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.15.10.0 (NJsonSchema v10.6.10.0 (Newtonsoft.Json v13.0.0.0))")]
internal class DateFormatConverter : System.Text.Json.Serialization.JsonConverter<System.DateTime>
{
    public override System.DateTime Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
    {
        var dateTime = reader.GetString();
        if (dateTime == null)
        {
            throw new JsonException("Unexpected JsonTokenType.Null");
        }

        return System.DateTime.Parse(dateTime);
    }

    public override void Write(System.Text.Json.Utf8JsonWriter writer, System.DateTime value, System.Text.Json.JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString("yyyy-MM-dd"));
    }
}

However, the JsonException throws a not found error, which is solved by adding using System.Text.Json statement. This gets deleted at build though, as the file is regenerated.

Is there a better way to implement the date format? Could I add the using statement in config somewhere?

Thanks

1 Answers

I used date, but should've been using date-time.

createdAt:
    type: string
    format: date-time

This should create:

[System.Text.Json.Serialization.JsonPropertyName("createdAt")]
public System.DateTimeOffset CreatedAt { get; set; } = default!;

No converter needed!

Related