在我们的项目中,我们正在以xml格式获取wcf服务的响应,我们希望使用datacontract序列化器对其进行反序列化。
以下是xml响应。
<ArrayOfCustomerData xmlns="http://schemas.datacontract.org/2004/07/PACRM.QCT">
<CustomerData>
<AccountID>String content</AccountID>
<AccountName1>String content</AccountName1>
</CustomerData>
<CustomerData>
<AccountID>String content</AccountID>
<AccountName1>String content</AccountName1>
</CustomerData>
</ArrayOfCustomerData>
我们编写了以下DataContract类来反序列化xml。
[DataContract]
public class ArrayOfCustomerData
{
[DataMember(Name="CustomerData")]
public CustomerData[] customerData { get; set; }
}
[DataContract]
public class CustomerData
{
[DataMember(IsRequired = true, Name = "AccountID")]
public string new_AccountID { get; set; }
[DataMember(IsRequired = true, Name = "AccountName1")]
public string new_accountname1 { get; set; }
}
反序列化的C#代码如下所示。
DataContractSerializer dcs = new DataContractSerializer(typeof(ArrayOfCustomerData));
ArrayOfCustomerData data=new ArrayOfCustomerData();
using (var stream = new StreamReader(response.GetResponseStream()))
{
var text=stream.ReadToEnd();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text));
XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(ms, Encoding.UTF8);
dcs.WriteObject(xdw, data);
}
当我检查data.cusotmerData时,它返回null。 有人可以为这个问题提供解决方案吗?谢谢!
答案 0 :(得分:0)
您不需要类ArrayOfCustomerData
- 这只是在预期的XML中添加了一个不必要的额外元素。您可以使用CustomerData[]
作为传递给DataContractSerializer
构造函数的类型,如下所示:
public class StackOverflow_24673714
{
const string XML = @"<ArrayOfCustomerData xmlns=""http://schemas.datacontract.org/2004/07/PACRM.QCT"">
<CustomerData>
<AccountID>String content ID 1</AccountID>
<AccountName1>String content name 1</AccountName1>
</CustomerData>
<CustomerData>
<AccountID>String content ID 2</AccountID>
<AccountName1>String content name 2</AccountName1>
</CustomerData>
</ArrayOfCustomerData>";
[DataContract(Name = "CustomerData", Namespace = "http://schemas.datacontract.org/2004/07/PACRM.QCT")]
public class CustomerData
{
[DataMember(IsRequired = true, Name = "AccountID")]
public string new_AccountID { get; set; }
[DataMember(IsRequired = true, Name = "AccountName1")]
public string new_accountname1 { get; set; }
}
public static void Test()
{
var ms = new MemoryStream();
var ws = new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true, Encoding = Encoding.UTF8 };
var w = XmlWriter.Create(ms, ws);
var dcs = new DataContractSerializer(typeof(CustomerData[]));
var obj = new CustomerData[] {
new CustomerData { new_AccountID = "String content 1", new_accountname1 = "String content 2" },
new CustomerData { new_AccountID = "String content 3", new_accountname1 = "String content 4" }
};
dcs.WriteObject(w, obj);
w.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
var cds = (CustomerData[])dcs.ReadObject(ms);
Console.WriteLine(cds.Length);
foreach (var cd in cds)
{
Console.WriteLine(" {0} - {1}", cd.new_AccountID, cd.new_accountname1);
}
}
}