【问题标题】:Use JSON.net Binder/TypeNameHandling for nested types对嵌套类型使用 JSON.net Binder/TypeNameHandling
【发布时间】:2016-01-14 10:58:11
【问题描述】:

使用 JSON.net,我想反序列化从抽象类继承的类型列表。我用过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。无法创建 C 类型的实例。类型是接口或抽象类,无法实例化。

我的类型看起来像这样;

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 并设置 BinderTypeNameHandling 没有区别。我发现 KnownTypesBinder.BindToType 根本没有被调用。 JSON.net 中是否有我遗漏的内容?

【问题讨论】:

    标签: c# json.net asp.net-web-api2


    【解决方案1】:

    在这里感觉很愚蠢。 JSON.net 使用的鉴别器称为"$type"。当我使用 curl 发送 POST 有效负载时,bash 尝试将 $type 解析为环境变量。由于没有这样的变量,最终的 JSON 只是 {"": "C"} 而不是 {"$type": "C"}

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多