我有一条正在尝试反序列化的记录:
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 线程。然而,两者似乎都没有提供完整的答案。两者都引用了 aDateOnlyConverter但我似乎无法在框架中的任何地方找到它。
我以前曾使用该[JsonPropertyConverter(typeof(CustomConverter))]属性来实现类似的事情。
所以我的问题实际上可以归结为:
这是DateOnlyConverter已经存在的东西,还是我必须自己实现?
如果答案是后者,我会这样做,然后将其作为该问题的答案发布给未来的读者。
Gur*_*ron 12
和转换器将随.NET 7DateOnly一起TimeOnly发布。
现在你可以创建一个看起来像这样的自定义的(for System.Text.Json, for 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/2022
| 归档时间: | 
 | 
| 查看次数: | 3926 次 | 
| 最近记录: |