Like many others already had the problem, I'm having problem with serializing a JSON from string/object to DateOnly.
I had already tried to implement solutions that were given in these posts.
I also use Newtonsoft.Json
.
https://github.com/JamesNK/Newtonsoft.Json/issues/2521
Thats my current 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. 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. (Parameter 's') at System.DateOnly.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style)
The JSON I am Posting
"postDate": {
"year": 2020,
"month": 10,
"day": 10,
"dayOfWeek": 0
},
Program.cs
builder.Services.AddControllers().AddNewtonsoftJson();