【发布时间】:2018-08-08 14:21:18
【问题描述】:
我正在尝试反序列化以下 XML:
<?xml version="1.0" encoding="UTF-8"?>
<jobInfo
xmlns="http://www.force.com/2009/06/asyncapi/dataload">
<id>asjdkfljasl;kdf</id>
<operation>query</operation>
<object>jsdkfjsakldjakl</object>
...
</jobInfo>
我有以下代码可以发出 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<jobInfo >(new List<MediaTypeFormatter>() {
new XmlMediaTypeFormatter { UseXmlSerializer = true },
new JsonMediaTypeFormatter()
});
但我得到了错误
没有 MediaTypeFormatter 可用于从媒体类型为“application/xml”的内容中读取“jobInfo”类型的对象,
我的 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<Type> only deserializing part of the response
我也尝试过(在使用 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; }
...
}
【问题讨论】:
-
为什么属性被列为私有?看起来您手动添加了这些值。这些名称也与 xml 标记名称不匹配。
-
我不确定,这就是 xsd.exe 针对特定类吐出的内容。我已经添加了我尝试过的另外两个“类”(参见
Bulkv1Job)。我认为这个错误具体是因为application/xml,而不是我如何设置课程,但我可能是错的。 -
您可能应该首先确保标准 XML 序列化和反序列化在单元测试中工作,以确保在
ReadAsAsync之前工作 -
@jdweng 我没有包含公共字段,它们现在已添加。
-
@Ryan 帮助我找到了我的问题!
标签: c# xml deserialization dotnet-httpclient