首页 > 其他分享 >API请求JSON特殊处理

API请求JSON特殊处理

时间:2022-12-15 11:23:25浏览次数:63  
标签:请求 DateTime writer public JSON API Guid options JsonSerializerOptions

API请求JSON特殊处理

场景

框架处理的请求和返回的转换后的string,有时候不是我们预期的样子。

可以使用 JsonSerializerOptions.Converters.Insert() 添加一个自定义的转换器,对特定的格式进行处理。

代码

builder.Services.AddControllers(options =>
{
}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;

    options.JsonSerializerOptions.Converters.Insert(0, new CustomDateTimeJsonConverter());
    options.JsonSerializerOptions.Converters.Insert(0, new CustomGuidJsonConverter());
});
public class CustomDateTimeJsonConverter : JsonConverter<DateTime?>
{
    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var originValue = reader.GetString();
        if (DateTime.TryParse(originValue, out DateTime dateTime))
        {
            return dateTime;
        }
        return null;
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss fff") ?? "");
    }
}


public class CustomGuidJsonConverter : JsonConverter<Guid>
{
    public override Guid Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var originValue = reader.GetString();
        if (Guid.TryParse(originValue, out Guid guid))
        {
            return guid;
        }
        return Guid.Empty;
    }

    public override void Write(Utf8JsonWriter writer, Guid value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString().ToUpper());
    }
}

标签:请求,DateTime,writer,public,JSON,API,Guid,options,JsonSerializerOptions
From: https://www.cnblogs.com/wosperry/p/16984544.html

相关文章