对嵌套类型使用 JSON.net Binder/TypeNameHandling
Use JSON.net Binder/TypeNameHandling for nested types
使用 JSON.net,我想反序列化从抽象 class 继承的类型列表。我用过 KnownTypesBinder
(source) 就像
var jsonSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.TypeNameHandling = TypeNameHandling.Auto;
jsonSettings.Binder = new KnownTypesBinder { KnownTypes = new List<Type> { ... } };
现在这在 WEB API modelbinder 中工作得很好; KnownTypesBinder.BindToType
被称为对象可以被反序列化。在 Web 应用程序的不同部分,我必须反序列化一个 JSON 字符串,所以我想重新使用相同的 JsonFormatter。根据文档,以下应该有效;
JsonConvert.DeserializeObject<T>(String, JsonSerializerSettings);
然而,当我这样做时:
JsonConvert.DeserializeObject<A>(jsonString, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings);
抛出以下错误:
JsonSerializationException. Could not create an instance of type C. Type is an interface or abstract class and cannot be instantiated.
我的类型看起来像这样;
class A {
public B B { get; set; }
}
class B {
public List<C> C { get; set; }
}
abstract class C { }
class C1: C { }
class C2: C { }
同时创建一个新的 JsonSerializerSettings 并设置 Binder
和 TypeNameHandling
没有区别。我发现 KnownTypesBinder.BindToType
根本没有被调用。 JSON.net 中是否有我遗漏的内容?
感觉这里很蠢。 JSON.net 使用的鉴别器称为 "$type"
。当我使用 curl
发送 POST 负载时,bash 试图将 $type
解析为环境变量。由于没有这样的变量,最终的 JSON 只是 {"": "C"}
而不是 {"$type": "C"}
.
使用 JSON.net,我想反序列化从抽象 class 继承的类型列表。我用过 KnownTypesBinder
(source) 就像
var jsonSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.TypeNameHandling = TypeNameHandling.Auto;
jsonSettings.Binder = new KnownTypesBinder { KnownTypes = new List<Type> { ... } };
现在这在 WEB API modelbinder 中工作得很好; KnownTypesBinder.BindToType
被称为对象可以被反序列化。在 Web 应用程序的不同部分,我必须反序列化一个 JSON 字符串,所以我想重新使用相同的 JsonFormatter。根据文档,以下应该有效;
JsonConvert.DeserializeObject<T>(String, JsonSerializerSettings);
然而,当我这样做时:
JsonConvert.DeserializeObject<A>(jsonString, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings);
抛出以下错误:
JsonSerializationException. Could not create an instance of type C. Type is an interface or abstract class and cannot be instantiated.
我的类型看起来像这样;
class A {
public B B { get; set; }
}
class B {
public List<C> C { get; set; }
}
abstract class C { }
class C1: C { }
class C2: C { }
同时创建一个新的 JsonSerializerSettings 并设置 Binder
和 TypeNameHandling
没有区别。我发现 KnownTypesBinder.BindToType
根本没有被调用。 JSON.net 中是否有我遗漏的内容?
感觉这里很蠢。 JSON.net 使用的鉴别器称为 "$type"
。当我使用 curl
发送 POST 负载时,bash 试图将 $type
解析为环境变量。由于没有这样的变量,最终的 JSON 只是 {"": "C"}
而不是 {"$type": "C"}
.