DataContractSerializer - 不反序列化子列表 - 列表<T>

DataContractSerializer - Not Deserializing Child List - List<T>

我正在尝试使用 DataContractSerializer 反序列化以下 XML。

<?xml version="1.0" encoding="utf-8"?>
<order>
  <header>
    <cust>1</cust>
    <bill>2</bill>
    <ship>3</ship>
    <nbr>123456</nbr>
  </header>
  <details>
    <detail>
      <nbr>123456</nbr>
      <part>1227</part>
      <qty>2</qty>
    </detail>
  </details>
</order>

我在反序列化子 <detail></detail> 段时遇到困难,它始终是 null。我的class结构如下:

[DataContract(Name = "order", Namespace ="")]
public class Order
{
    [DataMember(Name = "header", Order = 0)]
    public Head head { get; set; }
    [DataMember(Name = "details", Order = 1)]
    public Details details { get; set; }

    public Order()
    {
    }
}

[DataContract(Name = "header", Namespace ="")]
public class Head
{
    [DataMember(Name = "cust", Order = 0)]
    public string customerNbr { get; set; }
    [DataMember(Name = "bill", Order = 1)]
    public string billNbr { get; set; }
    [DataMember(Name = "ship", Order = 2)]
    public string shipmentNbr { get; set; }
    [DataMember(Name = "nbr", Order = 3)]
    public string orderNbr { get; set; }

    public Head()
    {

    }
}

[DataContract(Name = "details")]
public class Details
{
    [DataMember(Name = "detail", Order = 0)]
    public List<Detail> DetailList { get; set; }

    public Details()
    {
        this.DetailList = new List<Detail>();
    }
}

[DataContract(Name = "detail")]
public class Detail
{
    [DataMember(Name = "nbr", Order = 0)]
    public string orderNbr { get; set; }
    [DataMember(Name = "part", Order = 1)]
    public string partNbr { get; set; }
    [DataMember(Name = "qty", Order = 2)]
    public decimal orderQty { get; set; }

    public Detail()
    {

    }
}

在我的主程序中,我正在读取 XML 文档并使用以下内容对其进行反序列化:

XDocument readDoc = XDocument.Load(fileName);
Order createOrder = null;
DataContractSerializer ser = new DataContractSerializer(typeof(Order));
createOrder = (Order)ser.ReadObject(readDoc.CreateReader());

我该怎么做才能使详细信息段正确反序列化?

问题是您的数据协定 class 与实际 xml 结构要求的不同。

您可以通过对您的模型进行小的修改来解决这个问题。

Detail class 设置名称空间以匹配其他 class 中的名称空间,即:空白值。

[DataContract(Name = "detail", Namespace = "")]
public class Detail
{
    //same stuff here...
}

使您的详细信息class成为数据合同的集合。

[CollectionDataContract(Name = "details", Namespace = "")]
public class Details : Collection<Detail> { }

您可以查看 this 以了解有关收集和数据合同序列化的更多详细信息。

希望对您有所帮助!