【问题标题】:How to pass class type as property如何将类类型作为属性传递
【发布时间】:2020-02-17 10:52:07
【问题描述】:

public class Myclass { Public Type type {get;set;} }

Json 序列化时出现错误“无法从 System.String 转换或转换为 System.Type”

有人可以帮我吗?

【问题讨论】:

  • 您能否提供一个 json 示例,如果您尝试解析它会得到异常?
  • 我怀疑你想反序列化一个Type,而是一个类型名称,然后你可以将其解构为Type,对吗?

标签: c# json asp.net-core .net-core


【解决方案1】:

支持最简单的方法(未经测试)应该是(假设您在 Newtonsoft.Json 上):

public class MyClass
{
  private string _type;

  [JsonIgnore]
  public Type type {get => Assembly.GetType(_type, true, false); set => value.Fullname;}
}

【讨论】:

    【解决方案2】:

    您可以实现自己的转换器。看看这个例子,然后按照自己的方式实施。

    
    public class MyClass
    {
        [JsonConverter(typeof(JsonTypeConverter))]
        public Type Type { get; set; }
    }
    
    public class JsonTypeConverter: JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var type = value as Type;
            writer.WriteValue(type.Name);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
        }
    
        public override bool CanRead
        {
            get { return false; }
        }
    
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Type);
        }
    }
    
    
    

    【讨论】:

    • 请提供堆栈跟踪
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多