简体   繁体   English

NSwag - 在自动生成的 DTO 中为字符串属性使用日期格式

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

I am using NSwag to generate DTOs.我正在使用 NSwag 生成 DTO。 In the yaml I specify a property with a date format as follows:在 yaml 中,我指定了一个具有如下日期格式的属性:

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

This generates the C#:这将生成 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 :其中使用了DateFormatConverter新生成的 class :

[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.但是, JsonException会抛出not found错误,通过添加using System.Text.Json语句来解决。 This gets deleted at build though, as the file is regenerated.但是,随着文件的重新生成,这会在构建时被删除。

Is there a better way to implement the date format?有没有更好的方法来实现date格式? Could I add the using statement in config somewhere?我可以在 config 某处添加using语句吗?

Thanks谢谢

I used date , but should've been using date-time .我使用date ,但应该一直使用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!无需转换器!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM