问题描述:
Json序列化时会将Bool类型转换成string类型,然后反序列化时拿到的类型便于我的字段类型不匹配。
解决方法:
/// <summary>
/// 自定义布尔类型数据转换规则
/// </summary>
public class MyBoolConverter : JsonConverter
{
private const string TrueStr = "TRUE";
private const string FalseStr = "FALSE";
public override bool CanConvert(Type objectType) => true;
//反序列化
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string))
{
if ((string)reader.Value == TrueStr)
{
return true;
}
else
{
return false;
}
}
return false;
}
//序列化
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value.GetType() == typeof(bool))
{
bool result = (bool)value;
if (result)
{
writer.WriteValue(TrueStr);
}
else
{
writer.WriteValue(FalseStr);
}
}
}
}
如何使用
//在需要操作的类型定义中的字段/属性中加入该特性:
private class MyClass
{
[JsonConverter(typeof(MyBoolConverter))]
public bool MyBool;
}