gpt4 book ai didi

c# - 无法在 .NET 中反序列化 JSON 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 21:43:36 27 4
gpt4 key购买 nike

我有一个 JSON 字符串,我想将其反序列化为复合对象。

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>;

错误信息

Element ':item' contains data from a type that maps to the name ':Identifier'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'Identifier' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.

我做错了什么?

最佳答案

将一个空的 Namespace 添加到用于装饰您的 Identifier 类的 DataContract 属性:

[DataContract(Namespace = "")]
public class Identifier
{
[DataMember]
public string Version { get; set; }

[DataMember]
public string Value { get; set; }

[DataMember]
public int IdentifierType { get; set; }
}

你需要这个的原因是因为你的 JSON 中使用了 __type 属性,它对序列化器有特殊的意义。

关于c# - 无法在 .NET 中反序列化 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173952/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com