如何使用重新装配序列化DateOnly



我已经搜索了3-4天了,我几乎得到了答案,但仍然无法在代码中实现。事实上,我从来都不理解或无法通过查看文档来工作。:/

我还需要另一个建议,我使用日期只是因为我需要实现一个从日期到日期的日期范围过滤器,我不需要任何时间。这是正确的方式吗?还是应该使用DateTime。?

该链接解释关于C#DateOnly序列化

此链接解释有关重新安装序列化选项的修改(我想(

试试下面这个最小的可复制示例。当您从接口创建Refit实例时,可以传递一些选项,其中之一是可以附加自定义转换器的ContentSerializer属性。

using Refit;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions();
options.Converters.Add(new DateOnlyConverter());
options.Converters.Add(new TimeOnlyConverter());
var postmanEchoApi = RestService.For<IPostmanEchoApi>("https://postman-echo.com", new RefitSettings
{
ContentSerializer = new SystemTextJsonContentSerializer(options)
});
var echo = await postmanEchoApi.Echo(new Args
{
dateOnly = DateOnly.FromDateTime(DateTime.Now),
timeOnly = TimeOnly.FromDateTime(DateTime.Now),
});
Console.WriteLine(echo.args.dateOnly);
Console.WriteLine(echo.args.timeOnly);

public class DateOnlyConverter : JsonConverter<DateOnly>
{
private readonly string serializationFormat;
public DateOnlyConverter() : this(null) { }
public DateOnlyConverter(string? serializationFormat)
{
this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
}
public override DateOnly Read(ref Utf8JsonReader reader,
Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
return DateOnly.FromDateTime(DateTime.Parse(value!));
}
public override void Write(Utf8JsonWriter writer, DateOnly value,
JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString(serializationFormat));
}
public class TimeOnlyConverter : JsonConverter<TimeOnly>
{
private readonly string serializationFormat;
public TimeOnlyConverter() : this(null) { }
public TimeOnlyConverter(string? serializationFormat)
{
this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
}
public override TimeOnly Read(ref Utf8JsonReader reader,
Type typeToConvert, JsonSerializerOptions options)
{
var value = reader.GetString();
return TimeOnly.FromDateTime(DateTime.Parse(value!));
}
public override void Write(Utf8JsonWriter writer, TimeOnly value,
JsonSerializerOptions options)
=> writer.WriteStringValue(value.ToString(serializationFormat));
}
public class Args {
public DateOnly dateOnly { get; set; }
public TimeOnly timeOnly { get; set; }
}
public class Echo
{
public Args args { get; set; }
}
[Headers("user-agent: curl/7.79.1")]
public interface IPostmanEchoApi
{
[Get("/get")]
Task<Echo> Echo(Args queryParams);
}

相关内容

  • 没有找到相关文章

最新更新