You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.8 KiB
55 lines
1.8 KiB
using System; |
|
using System.Collections.Generic; |
|
using System.Linq; |
|
using System.Text; |
|
using System.Text.Json; |
|
using System.Text.Json.Serialization; |
|
using System.Threading.Tasks; |
|
|
|
namespace Elight.Utility |
|
{ |
|
/// <summary> |
|
/// 自定义 NullableConverter 解决可为空类型字段入参“”空字符触发转换异常问题 |
|
/// </summary> |
|
/// <typeparam name="T"></typeparam> |
|
public class NullableConverter<T> : JsonConverter<T?> where T:struct |
|
{ |
|
public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
|
{ |
|
if (reader.TokenType == JsonTokenType.String) |
|
{ |
|
if (string.IsNullOrEmpty(reader.GetString()) || string.IsNullOrWhiteSpace(reader.GetString())) |
|
{ |
|
return null; |
|
} |
|
} |
|
return JsonSerializer.Deserialize<T>(ref reader, options); |
|
} |
|
|
|
|
|
public override void Write(Utf8JsonWriter writer, T? value, JsonSerializerOptions options) |
|
{ |
|
JsonSerializer.Serialize(writer, value!.Value, options); |
|
} |
|
|
|
} |
|
|
|
public class DateTimeNullableConverter : JsonConverter<DateTime?> |
|
{ |
|
public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
|
{ |
|
if (reader.TokenType == JsonTokenType.String) |
|
{ |
|
if (DateTime.TryParse(reader.GetString(), out DateTime date)) return date; |
|
return default(DateTime?); |
|
|
|
} |
|
return reader.GetDateTime(); |
|
} |
|
|
|
public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) |
|
{ |
|
writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss")); |
|
} |
|
} |
|
}
|
|
|