【问题标题】:ReadAsAsync Class using XmlMediaTypeFormatter or other Deserialization使用 XmlMediaTypeFormatter 或其他反序列化的 ReadAsAsync 类
【发布时间】: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.xmlxsd.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


【解决方案1】:

经过测试

var s = await response.content.readasstringasync();
var buffer = encoding.utf8.getbytes(s);
using (var stream = new memorystream(buffer)) {
    var serializer = new xmlserializer(typeof(jobinfo)); // FAILED LINE
    var jobinfo = (jobinfo)serializer.deserialize(stream);
    //then do whatever you want
    return jobinfo;
}

我发现由于类保护错误,上述行的序列化程序失败。 确保 jobInfo 类是公开且可访问的,错误消失并且 deserialize(stream) 工作。

删除该代码并使用readAsAsync&lt;jobInfo&gt;(...) 之后可以正常工作。

感谢@Ryan

【讨论】:

    【解决方案2】:

    嗯,我不是肥皂专家,但如果我没记错的话,它应该在你的属性上使用 [DataMember] 和在你的类上使用 [DataContract(NameSpace="jobInfo")] 之类的装饰器。 您可以看到,在您提供的第一个建议中,使用 [XmlRoot] 和 [XmlElement]

    你也可以看看WCF Datacontract, some fields do not deserialize,也许对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多