10

我有一个问题DataContractSerializer。我使用它从 ASP.NET Web 服务返回的 XML 创建类实例。但实际上数据的来源在这里并不重要。为了使整个案例更容易调试,我创建了一个简单的测试项目,只有序列化和问题仍然存在。

这是我的 XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<GetTestURL p1:type="MyApp.GetTestUrlInfo" xmlns:p1="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
  <TestURL>http://bing.com</TestURL>
  <UserCount p1:type="Edm.Int32">1</UserCount>
  <InitialCount p1:type="Edm.Int32">1</InitialCount>
  <AverageExecutionTime p1:type="Edm.Int32">43</AverageExecutionTime>
</GetTestURL>

我试图将 XML 反序列化为的类:

[DataContract(Name = "GetTestURL", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
public class TestInfo
{
    [DataMember(Name = "TestURL")]
    public Uri TestUri { get; private set; }

    [DataMember(Name = "UserCount")]
    public int UserCount { get; private set; }

    [DataMember(Name = "InitialCount")]
    public int InitialCount { get; private set; }

    [DataMember(Name = "AverageExecutionTime")]
    public int AverageExecutionTime { get; private set; }
}

还有我的序列化助手类:

public static class SerializationHelper<T>
{
    private static DataContractSerializer _serializer = new DataContractSerializer(typeof(T));

    public static T Deserialize(Stream source)
    {
        return (T)_serializer.ReadObject(source);
    }
}

测试代码:

// Test program
public static void Main()
{
    TestInfo info = null;
    using (var stream = File.Open("Input.xml", FileMode.Open, FileAccess.Read))
    {
        info = SerializationHelper<TestInfo>.Deserialize(stream);
    }
}

在方法结束时设置刹车点后,我看到以下内容:

在此处输入图像描述

如您所见,两者AverageExecutionTimeInitialCount都没有反序列化并且具有int默认值。它们应该设置为43and 1,因为这些值在 XML 中。

对我来说更奇怪的是,该UserCount属性是正确的,但实际上它与根本不起作用的两个没有任何区别。唯一不同的是元素名称。

4

1 回答 1

12

我设法通过更新数据合同让它工作。与订单有关。当我将 Uri 设为必需属性时,它引发了异常,因此它可能与加载顺序有关。

    [DataContract(Name = "GetTestURL", Namespace = "http://schemas.microsoft.com/ado/2007/08/dataservices")]
    public class TestInfo
    {
        public TestInfo() { }
        public TestInfo(Uri uri, int userCount, int initialCount, int averageExecutionTime)
        {
            TestUri = uri;
            UserCount = userCount;
            InitialCount = initialCount;
            AverageExecutionTime = averageExecutionTime;
        }
        [DataMember(Name = "TestURL", IsRequired=true, Order=1)]
        public Uri TestUri { get; private set; }

        [DataMember(Name = "UserCount", IsRequired=true, Order=2)]
        public int UserCount { get; private set; }

        [DataMember(Name = "InitialCount", IsRequired=true, Order=3)]
        public int InitialCount { get; private set; }

        [DataMember(Name = "AverageExecutionTime", IsRequired=true, Order=4)]
        public int AverageExecutionTime { get; private set; }
    }
于 2013-11-14T23:17:33.650 回答