[英]NSwag - using date format for string property in auto-generated DTOs
我正在使用 NSwag 生成 DTO。 在 yaml 中,我指定了一个具有如下日期格式的属性:
User:
type: object
additionalProperties: false
properties:
createdAt:
type: string
format: date
这将生成 C#:
[System.Text.Json.Serialization.JsonPropertyName("createdAt")]
[System.Text.Json.Serialization.JsonConverter(typeof(DateFormatConverter))]
public System.DateTimeOffset CreatedAt { get; set; } = default!;
其中使用了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"));
}
}
但是, JsonException
会抛出not found
错误,通过添加using System.Text.Json
语句来解决。 但是,随着文件的重新生成,这会在构建时被删除。
有没有更好的方法来实现date
格式? 我可以在 config 某处添加using
语句吗?
谢谢
我使用date
,但应该一直使用date-time
。
createdAt:
type: string
format: date-time
这应该创建:
[System.Text.Json.Serialization.JsonPropertyName("createdAt")]
public System.DateTimeOffset CreatedAt { get; set; } = default!;
无需转换器!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.