API请求JSON特殊处理
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());
}
}