Skip to main content
 首页 » 编程设计

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

2024年02月13日22arxive

我有一个 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 属性,它对序列化器有特殊的意义。