简体   繁体   English

如何在 asp.net-core 6.0 中构建 DateOnlyJsonConverter

[英]How to build a DateOnlyJsonConverter in asp.net-core 6.0

Like many others already had the problem, I'm having problem with serializing a JSON from string/object to DateOnly.像许多其他人已经遇到问题一样,我在将 JSON 从字符串/对象序列化为 DateOnly 时遇到问题。

I had already tried to implement solutions that were given in these posts.我已经尝试实施这些帖子中给出的解决方案。 I also use Newtonsoft.Json .我也使用Newtonsoft.Json

https://github.com/JamesNK/Newtonsoft.Json/issues/2521 https://github.com/JamesNK/Newtonsoft.Json/issues/2521

Thats my current DTO那是我目前的 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; }
}

If I build the converter like this, I get the problem that reader.Value can be null.如果我像这样构建转换器,我会遇到reader.Value可以为空的问题。 If I bypass the warning, which I do, I get this error.如果我绕过警告,我会得到这个错误。

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: Value cannot be null. System.ArgumentNullException:值不能为空。 (Parameter 's') at System.DateOnly.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) System.DateOnly.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) 处的(参数's')

The JSON I am Posting我发布的 JSON

   "postDate": {
      "year": 2020,
      "month": 10,
      "day": 10,
      "dayOfWeek": 0
    },

Program.cs程序.cs

builder.Services.AddControllers().AddNewtonsoftJson();

To use the converter from this answer you need to post data in correct format.要使用此答案中的转换器,您需要以正确的格式发布数据。 The this DateOnlyJsonConverter specifies it "yyyy-MM-dd" so your post body should look like:这个DateOnlyJsonConverter将其指定为"yyyy-MM-dd" ,因此您的帖子正文应如下所示:

{
   "postDate": "2020-10-10"
}

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

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