从山证v2.3.0拷贝
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace YLErp.Serialization
|
||||
{
|
||||
/// <summary>
|
||||
/// 兼容Net Framework 如果为null,转为默认值
|
||||
/// </summary>
|
||||
public class CustomIntConvert : JsonConverter<int>
|
||||
{
|
||||
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.String || reader.TokenType == JsonTokenType.Null)
|
||||
{
|
||||
var str = reader.GetString();
|
||||
if (string.IsNullOrWhiteSpace(str) || str.Trim() == "null" || str == "NaN")
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (int.TryParse(str, out var d))
|
||||
{
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
return reader.GetInt32();
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteNumberValue(value);
|
||||
}
|
||||
|
||||
public static readonly CustomIntConvert Default;
|
||||
|
||||
static CustomIntConvert()
|
||||
{
|
||||
Default = new CustomIntConvert();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 兼容Net Framework 如果为null,转为默认值
|
||||
/// </summary>
|
||||
public class CustomBoolConvert : JsonConverter<bool>
|
||||
{
|
||||
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.String|| reader.TokenType == JsonTokenType.Null)
|
||||
{
|
||||
var str = reader.GetString();
|
||||
if (string.IsNullOrWhiteSpace(str) || str.Trim() == "null" || str == "NaN")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (bool.TryParse(str, out var d))
|
||||
{
|
||||
return d;
|
||||
}
|
||||
}
|
||||
|
||||
return reader.GetBoolean();
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteBooleanValue(value);
|
||||
}
|
||||
|
||||
public static readonly CustomBoolConvert Default;
|
||||
|
||||
static CustomBoolConvert()
|
||||
{
|
||||
Default = new CustomBoolConvert();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user