我有一个C#MVC应用程序,它将数据作为JSON字符串存储在XML文档中,也存储在MySQL数据库表中.
最近我收到了在MySQL数据库字段中存储JSON字符串的要求,要通过Newtonsoft.Json转换为C#对象,所以我决定实现一个TypeConverter将JSON字符串转换为自定义C#模型.
不幸的是,当TypeConverter属性添加到我的C#Model时,我无法在我的解决方案中的任何地方使用以下命令来反序列化我的JSON字符串:
JsonConvert.DeserializeObject<Foo>(json);
Run Code Online (Sandbox Code Playgroud)
删除属性可以解决问题但是这会阻止我将MySQL DB字段转换为自定义C#对象.
这是我添加了TypeConverter属性的C#模型:
using System.ComponentModel;
[TypeConverter(typeof(FooConverter))]
public class Foo
{
public bool a { get; set; }
public bool b { get; set; }
public bool c { get; set; }
public Foo(){}
}
Run Code Online (Sandbox Code Playgroud)
这是我的TypeConverter类:
using Newtonsoft.Json;
using System;
using System.ComponentModel;
public class FooConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
{
if (sourceType == typeof(string))
{
return true; …Run Code Online (Sandbox Code Playgroud)