datacontractserializer deserialize list<> alway

2019-08-12 09:30发布

I'm deserializing data received from a web-service.

The problem is that the deserialization of List returns an empty list and no exception are generated. Can you help me figure out why? We have tried several possible syntax. The code below is the closest to the correct solution but we cannot deserialize correctly as a list of classes.

<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>

Code:

 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;
        }    

Class:

 [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条回答
放荡不羁爱自由
2楼-- · 2019-08-12 10:00

The data contract element name is "MAASUsers" but in the xml the element is named "MaasUsers". The data contract serializer is case sensitive so it will NOT match these two up.

查看更多
劳资没心,怎么记你
3楼-- · 2019-08-12 10:03

Try to add Order and Name attribute to the Contract class. Sample:

[DataMember(Order = 1, Name = "firstName")]
查看更多
登录 后发表回答