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

标签 c# .net json deserialization

我有一个 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/

相关文章:

c# - 自定义 ASP.NET MVC ActionFilterAttribute - 永远不会调用 Hook

c# - 在 Unity 中,是否可以从类型别名解析类型?

c# - 记录和恢复应用程序状态以快速启动 .NET 应用程序

javascript - 使用 Jquery 用索引或位置而不是键名解析 JSON 对象?

android - 改造。安卓。我可以在不解析的情况下将 json 对象下载到 String 吗?

c# - 当我使用 iText 从 PDF 文件中提取文本时,我从以前的页面中获取值

c# - ASP.NET 动态添加列到 Gridview

c# - Selenium中使用FireFoxDriver时,如何知道页面Url?

.net - Entity Framework 模型中的共享实体

json - 使用 ReactJS 和 AJAX 更新页面内容