如何解决Json 灭菌不适用于具有 TypeConverter 属性的复杂对象
我创建了一个类名作为 TFDisplay,一个 [TypeConverter()]
属性应用于它。
当我调用 JsonConvert.SerializeObject(tfdisplayInstance)
时,它不会将整个类对象消毒为 Json sting,而是只考虑类的一个属性进行序列化。
我知道了,为什么它只考虑一个属性!因为 TypeConverter
基类的 ConvertTo 方法已被覆盖。
这个覆盖是为了某些功能而特意完成的,但与此同时,当 Json 序列化为 TFDisplay 类实例运行时,我还需要整个类实例应该被序列化。
这是我项目中的一个类
[Serializable]
[TypeConverter(typeof(TFDisplayTypeConverter))]
public class TFDisplay : TFType,ITFConvertible,IComparable<TFDisplay>
{
public TFDisplay() { }
public TFDisplay(object value,string text) { Value = value; Text = text; }
public TFDisplay(object value)
{
Value = value;
}
public static implicit operator TFDisplay(string value)
{
var result = new TFDisplay()
{
Value = value
};
return result;
}
public static implicit operator TFDisplay(int value)
{
var result = new TFDisplay()
{
Value = value
};
return result;
}
public static implicit operator string(TFDisplay dt)
{
if (dt is null)
return string.Empty;
else if (string.IsNullOrEmpty(dt.Text))
return string.Empty;
return dt.Text;
}
[NonSql()]
public object Value { get; set; }
[NonSql()]
public string Text { get; set; } = "";
public int CompareTo(TFDisplay other)
{
return this.Text.CompareTo(other.Text);
}
}
类型转换实现
public class TFDisplayTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context,Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context,sourceType);
// return sourceType == typeof(string) || base.CanConvertFrom(context,sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context,System.Globalization.CultureInfo culture,object value)
{
if (value is string)
return new TFDisplay(Convert.ToString(value));
return base.ConvertFrom(context,culture,value);
}
public override object ConvertTo(ITypeDescriptorContext context,object value,Type destinationType)
{
if (destinationType == typeof(string))
return ((TFDisplay)value).Text; //Because of this line of code getting only 'Text'property value,but this is also required for other purposes
return base.ConvertTo(context,value,destinationType);
}
}
TFDisplay 类对 Json 字符串的使用
TFDisplay country = new TFDisplay(1,"India");
string jsonStr = JsonConvert.SerializeObject(country);
//It returns only "India" as output,which I expecting should return complete json of TFDisplay class
预期的 Json 输出
"{\"Value\":1,\"Text\":\"India\",\"IsActive\":null}"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。