63 lines
1.7 KiB
C#
63 lines
1.7 KiB
C#
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Converters;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace YLErp.Core.Serialization
|
|
{
|
|
public class CustomBoolConverter : JsonConverter
|
|
{
|
|
public override bool CanConvert(Type objectType)
|
|
{
|
|
return objectType == typeof(bool) || objectType == typeof(bool?);
|
|
}
|
|
|
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
{
|
|
if (reader.TokenType == JsonToken.String || reader.TokenType == JsonToken.Null)
|
|
{
|
|
var str = reader.Value.ToString();
|
|
if (string.IsNullOrEmpty(str))
|
|
{
|
|
if (IsNullableType(objectType))
|
|
{
|
|
return null;
|
|
}
|
|
return false;
|
|
}
|
|
else if(bool.TryParse(str, out var d))
|
|
{
|
|
return d;
|
|
}
|
|
}
|
|
return reader.ReadAsBoolean();
|
|
}
|
|
|
|
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
{
|
|
if (value == null)
|
|
{
|
|
writer.WriteNull();
|
|
return;
|
|
}
|
|
|
|
bool bValue = (bool)value;
|
|
writer.WriteValue(bValue);
|
|
}
|
|
|
|
|
|
private bool IsNullableType(Type t)
|
|
{
|
|
if (t.IsGenericType)
|
|
{
|
|
return t.GetGenericTypeDefinition() == typeof(Nullable<>);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
}
|