即使我在我试图反序列化的对象上指定类型,我也收到 json.net 的“类型是接口,无法实例化”反序列化错误
private static JsonSerializerSettings settings = new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto };
/// <summary>
/// Returns an object created from the jObject and placed in a stub object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jObj"></param>
/// <returns></returns>
public static T FromJObject<T>(JToken jObj)
{
if (jObj == null)
{
jObj = new JObject();
}
if (jObj is JValue)
{
return (T)((JValue)jObj).Value;
}
else
{
return (T)JsonConvert.DeserializeObject<T>(jObj.ToString(), settings);
}
}
这是乔布斯
{
"Id": 2,
"Name": "Name",
"JsonMapEnum": 0,
"Validations": [
{
"Id": 1,
"$type": "JsonMap.Default.JValidation, JsonMap"
}
],
"JSType": 3,
"SubJsonMapEnum": -1,
"$type": "JsonMap.Default.JAttribute, JsonMap"
}
这是错误
Could not create an instance of type JsonMap.Interfaces.IValidation. Type is an interface or abstract class and cannot be instantated. Path 'Validations[0].Id'
看起来它正试图将 Id 转换为 Validation 对象。为什么?
这些是我的类型实现的接口
public interface IJsonMap
{
long Id { get; set; }
String Name { get; set; }
LazyEnum JsonMapEnum { get; set; }
}
public interface IAttribute : IJsonMap
{
IEnumerable<IValidation> Validations { get; set; }
LazyEnum JSType { get; set; }
LazyEnum SubJsonMapEnum { get; set; }
}
public interface IValidation : IJsonMap
{
IEnumerable<IArgument> Arguments { get; set; }
}
这是电话
FromJObject<JAttribute>(CreationJObj)
JAttribute 实现 IAttribute