[英]How to build a DateOnlyJsonConverter in asp.net-core 6.0
像许多其他人已经遇到问题一样,我在将 JSON 从字符串/对象序列化为 DateOnly 时遇到问题。
我已经尝试实施这些帖子中给出的解决方案。 我也使用Newtonsoft.Json
。
https://github.com/JamesNK/Newtonsoft.Json/issues/2521
那是我目前的 DTO
using Newtonsoft.Json;
using JsonSerializer = Newtonsoft.Json.JsonSerializer;
namespace ......;
public class PostDto
{
public PostDto(
DateOnly postDate
)
{
PostDate = postDate;
}
[JsonConverter(typeof(DateOnlyJsonConverter))]
public DateOnly PostDate { get; }
}
如果我像这样构建转换器,我会遇到reader.Value
可以为空的问题。 如果我绕过警告,我会得到这个错误。
public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
private const string Format = "yyyy-MM-dd";
public override void WriteJson(JsonWriter writer, DateOnly value, JsonSerializer serializer) =>
writer.WriteValue(value.ToString(Format, CultureInfo.InvariantCulture));
public override DateOnly ReadJson(
JsonReader reader, Type objectType, DateOnly existingValue, bool hasExistingValue,
JsonSerializer serializer) => DateOnly.ParseExact(((string)
reader.Value)!, Format, CultureInfo.InvariantCulture);
}
System.ArgumentNullException:值不能为空。 System.DateOnly.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) 处的(参数's')
我发布的 JSON
"postDate": {
"year": 2020,
"month": 10,
"day": 10,
"dayOfWeek": 0
},
程序.cs
builder.Services.AddControllers().AddNewtonsoftJson();
要使用此答案中的转换器,您需要以正确的格式发布数据。 这个DateOnlyJsonConverter
将其指定为"yyyy-MM-dd"
,因此您的帖子正文应如下所示:
{
"postDate": "2020-10-10"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.