我有这样的记录,我正试图反序列化:
public record MementoTimeEntry
(
Guid Id,
Guid ActivityId,
string UserId,
string Title,
TimeOnly StartTime,
TimeOnly FinishTime,
DateOnly Start,
DateOnly ActivityDate,
int Hours
);但是,我得到了以下错误:
System.NotSupportedException: Serialization and deserialization of 'System.DateOnly' instances are not supported.谢天谢地,问题是什么,这是非常清楚的。
所以,我读过这个答案和这个GitHub线程。然而,两者似乎都没有提供完整的答案。两者都引用了DateOnlyConverter,但我似乎在框架中找不到这一点。
我以前使用过[JsonPropertyConverter(typeof(CustomConverter))]属性来实现类似的功能。
所以我的问题归结为:
这是DateOnlyConverter已经存在的东西,还是我必须自己实现它?
如果答案是后者,我会这样做,然后把它作为这个问题的答案,供未来的读者使用。
发布于 2022-07-14 17:05:19
DateOnly和TimeOnly转换器将与.NET 7一起发布。
现在,您可以创建一个如下所示的自定义模型(对于System.Text.Json,对于Json.NET -参见这答案):
public class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
private const string Format = "yyyy-MM-dd";
public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateOnly.ParseExact(reader.GetString(), Format, CultureInfo.InvariantCulture);
}
public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(Format, CultureInfo.InvariantCulture));
}
}其中一个可能的用途是:
class DateOnlyHolder
{
// or via attribute [JsonConverter(typeof(DateOnlyJsonConverter))]
public DateOnly dt { get; set; }
}
var jsonSerializerOptions = new JsonSerializerOptions
{
Converters = { new DateOnlyJsonConverter() }
};
var serialized = JsonSerializer.Serialize(new DateOnlyHolder{dt = new DateOnly(2022,1,2)}, jsonSerializerOptions);
Console.WriteLine(serialized); // prints {"dt":"2022-01-02"}
var de = JsonSerializer.Deserialize<DateOnlyHolder>(serialized, jsonSerializerOptions);
Console.WriteLine(de.dt); // prints 1/2/2022https://stackoverflow.com/questions/72984063
复制相似问题