使用XmlMediaTypeFormatter或其他反序列化方法的ReadAsAsync类
使用XmlMediaTypeFormatter或其他反序列化方法的ReadAsAsync类
我正在尝试反序列化以下XML内容:
asjdkfljasl;kdf query ...
我有以下代码进行POST请求,并且请求成功,但无法反序列化为我的类。
client.DefaultRequestHeaders.Add("X-SFDC-Session", binding.SessionHeaderValue.sessionId); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", binding.SessionHeaderValue.sessionId); var content = new StringContent(createJobXml, Encoding.UTF8, "application/xml"); content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); HttpResponseMessage response = await client.PostAsync( $"https://{SERVER_INSTANCE}.salesforce.com/services/async/43.0/job", content ); response.EnsureSuccessStatusCode(); jobInfo job = await response.Content.ReadAsAsync(new List () { new XmlMediaTypeFormatter { UseXmlSerializer = true }, new JsonMediaTypeFormatter() });
但我收到以下错误消息:
没有可用的MediaTypeFormatter来读取类型为'jobInfo'的对象,其媒体类型为'application/xml'的内容,
我的jobInfo是使用xsd.exe doc.xml
和xsd.exe doc.xsd /classes
生成的。
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.force.com/2009/06/asyncapi/dataload")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.force.com/2009/06/asyncapi/dataload", IsNullable = false)] public partial class jobInfo { private string idField; private string operationField; private string objectField; ... public string id { get { return this.idField; } set { this.idField = value; } } public string operation { get { return this.operationField; } set { this.operationField = value; } } ... }
我需要做什么才能正确反序列化?
这建议我将其读取为字符串:
How to use HttpClient to read an XML response?
但这则建议应该“正常工作”:
HttpClient ReadAsAsync
我之前还尝试过(在使用xsd将xml转换为类之前使用的是Bulkv1Job类):
[DataContract] public class Bulkv1Job { [DataMember] string id { get; set; } [DataMember] string operation { get; set; } [DataMember] string @object { get; set; } ... }
和
[XmlRoot("jobInfo")] public class Bulkv1Job { [XmlElement("id")] string id { get; set; } [XmlElement("operation")] string operation { get; set; } ... }
问题的原因是在使用XmlMediaTypeFormatter或其他反序列化方法时,可能会遇到无法正确反序列化的问题。
解决方法可能是添加必要的装饰器,如[DataMember]用于属性上,以及[DataContract(NameSpace="jobInfo")]用于类上。另外,也可以参考链接中的建议,例如使用[XmlRoot]和[XmlElement]进行修饰。