【发布时间】:2013-08-11 16:09:43
【问题描述】:
我有一个 JSON 字符串,我想反序列化为 Compound 对象。
JSON
[{
"Name":"Aspirin",
"Identifiers":[{
"__type":"Identifier",
"IdentifierType":0,
"Value":"InChI=1\/C9H8O4\/c1-6(10)13-8-5-3-2-4-7(8)9(11)12\/h2-5H,1H3,(H,11,12)",
"Version":"v1.02b"
},{
"__type":"Identifier",
"IdentifierType":0,
"Value":"InChI=1S\/C9H8O4\/c1-6(10)13-8-5-3-2-4-7(8)9(11)12\/h2-5H,1H3,(H,11,12)",
"Version":"v1.02s"
},{
"__type":"Identifier",
"IdentifierType":2,
"Value":"BSYNRYMUTXBXSQ-UHFFFAOYAW",
"Version":"v1.02b"
},{
"__type":"Identifier",
"IdentifierType":2,
"Value":"BSYNRYMUTXBXSQ-UHFFFAOYSA-N",
"Version":"v1.02s"
},{
"__type":"Identifier",
"IdentifierType":1,
"Value":"CC(=O)Oc1ccccc1C(=O)O",
"Version":"OEChem"
}]
}]
复合类
[KnownType(typeof(List<Identifier>))]
[DataContract]
public class Compound
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<Identifier> Identifiers { set; get; }
}
标识符类
[DataContract]
public class Identifier
{
[DataMember]
public string Version { get; set; }
[DataMember]
public string Value { get; set; }
[DataMember]
public int IdentifierType { get; set; }
}
反序列化代码
DataContractJsonSerializer ser =
new DataContractJsonSerializer(
typeof(IEnumerable<Compound>),
new Type[] { typeof(List<Identifier>) }
);
IEnumerable<Compound> compounds =
ser.ReadObject(
new MemoryStream(Encoding.UTF8.GetBytes(response))
) as IEnumerable<Compound>;
错误信息
元素 ':item' 包含映射到名称的类型的数据 ':标识符'。反序列化器不知道映射的任何类型 到这个名字。考虑使用 DataContractResolver 或添加类型 对应于已知类型列表的“标识符” - 对于 例如,通过使用 KnownTypeAttribute 属性或将其添加到 传递给 DataContractSerializer 的已知类型列表。
我做错了什么?
【问题讨论】:
-
这对我有用(复制/粘贴你所拥有的)。我假设响应是 JSON,你是如何得到响应的?您能否验证响应部分是否有效?
-
嗯...这正是我传递给反序列化函数的 JSON。我在调试器中检查了它。
标签: c# .net json deserialization