datacontractserializer反序列化列表<>总是空的

时间:2014-04-14 14:23:10

标签: c# xml web-services deserialization datacontract

我正在对从网络服务收到的数据进行反序列化。

问题是List的反序列化返回一个空列表,并且不会生成任何异常。你能帮我搞清楚为什么吗? 我们尝试了几种可能的语法。下面的代码最接近正确的解决方案,但我们不能正确地反序列化为类列表。

<ArrayOfBatch xmlns="http://schemas.datacontract.org/2004/07/myns" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

<MaasBatch>
<BatchName>All Users</BatchName>
<Users>
<MaasUsers>
    <firstName>bob</firstName>
    <lastName>thetest</lastName>        
    <sourceEmail>bob@source.com</sourceEmail>
    <sourceTenantID>111</sourceTenantID>
    <targetEmail>bob@target.com</targetEmail>
    <targetTenantID>222</targetTenantID>
</MaasUsers>
</Users>
</MaasBatch>
</ArrayOfBatch>

代码:

 List<MAASBatch> lstMaasBatches = null;
        try
        {                
            string target = string.Empty;
            using (var response = request.GetResponse())
            {
                Stream streamReader = response.GetResponseStream();
                DataContractSerializer serializer = new DataContractSerializer(typeof(List<MAASBatch>));
                lstMaasBatches = (List<MAASBatch>)serializer.ReadObject(streamReader);
                streamReader.Close();                   
            }
            return lstMaasBatches;
        }
        catch (Exception exc)
        {
            return lstMaasBatches;
        }    

类别:

 [DataContract(Name = "MAASBatch", Namespace = "http://schemas.datacontract.org/2004/07/myns")]
[KnownType(typeof(MAASUsers))]
public class MAASBatch
{
    [DataMember]
    public string BatchName { get; set; }
    [DataMember]
    public List<MAASUsers> Users { get; set; }

    [OnDeserializing]
    internal void OnDeserializingCallBack(StreamingContext streamingContext)
    {
        this.Users = new List<MAASUsers>();
    }
}

[DataContract(Name = "MAASUsers", Namespace = "http://schemas.datacontract.org/2004/07/myns")]    
public class MAASUsers
{
     [DataMember]
    public string firstName { get; set; }
     [DataMember]
    public string lastName { get; set; }
     [DataMember]
    public string sourceEmail { get; set; }
     [DataMember]
    public int sourceAgentID { get; set; }
     [DataMember]
    public string targetEmail { get; set; }
     [DataMember]
    public int targetAgentID { get; set; }

}

2 个答案:

答案 0 :(得分:0)

尝试将Order和Name属性添加到Contract类。 样本:

[DataMember(Order = 1, Name = "firstName")]

答案 1 :(得分:0)

数据合约元素名称是“MAASUsers”,但在xml中元素名为“MaasUsers”。数据协定序列化程序区分大小写,因此它们不会匹配这两个。