微信支付接口返回的数据是xml格式并且包含CDATA节点,使用默认的反序列化类不能正常反序列化,因此需要自定义反序列化方案,如下方法可正常解析:
public static T GetXmlObject<T>(string xml)
{
Type type = typeof(T);
string fullName = type.FullName;
XmlSerializer serializer = null;
XmlAttributes attributes = new XmlAttributes
{
XmlRoot = new XmlRootAttribute("xml")
};
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(type, attributes);
serializer = new XmlSerializer(type, overrides);
object obj2 = null;
try
{
Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
try
{
obj2 = serializer.Deserialize(stream);
}
finally
{
if (!ReferenceEquals(stream, null))
{
stream.Dispose();
}
}
}
catch (Exception)
{
return default(T);
}
return (T)obj2 ;
}