【发布时间】:2017-02-28 04:34:46
【问题描述】:
我只是花了很长时间试图解决这个问题,所以我在这里发帖以防其他人犯和我一样的错误。
所以,为了复制这种情况,我只创建了几个具有基本继承的类:
public abstract class Foo
{
public string Name { get; set; }
}
public class Bar : Foo
{
public int SomethingSpecial { get; set; }
}
public class Baz : Foo
{
public string SomethingMundane { get; set; }
}
现在,我希望能够获取一个 json 字符串,并解析回 Foo 的具体实现,而无需事先知道 json 代表哪种类型。 JSON.Net 通过使用 $type 变量来查找对象的类型来处理这个问题:
{
"$type": "MyNamespace.Bar",
"Name": "Resources",
"SomethingSpecial": 42
}
在反序列化对象时,您可能希望在 JsonSerializerSettings 中指定类型处理选项和自定义绑定器,但这是可选的。
我遇到的问题是,当从 Web 客户端发布 json 时,对象没有被反序列化,而是抛出异常,或者在 ASP.Net 中的 POST 参数的情况下,值即将到来作为null。
【问题讨论】:
标签: asp.net asp.net-web-api json.net