简体   繁体   English

使用XmlMediaTypeFormatter或其他反序列化的ReadAsAsync类

[英]ReadAsAsync Class using XmlMediaTypeFormatter or other Deserialization

I am trying to deserialize the following XML: 我正在尝试反序列化以下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>

I have the following code that makes the POST request and works successfully, but cannot deserialize into my class. 我有以下代码可以发出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()
});

But I get the error 但是我得到了错误

No MediaTypeFormatter is available to read an object of type 'jobInfo ' from content with media type 'application/xml', 没有MediaTypeFormatter可用于从媒体类型为'application / xml'的内容读取'jobInfo'类型的对象,

my jobInfo was generated using xsd.exe doc.xml , xsd.exe doc.xsd /classes 我的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;
        }
    }
    ...
 }

What am I missing in order to deserialize this correctly? 为了正确反序列化,我缺少什么?

This suggests that I should just read it as a string: 这表明我应该将其作为字符串读取:

How to use HttpClient to read an XML response? 如何使用HttpClient读取XML响应?

but this suggests that it should "just work" 但这表明它应该“正常工作”

HttpClient ReadAsAsync<Type> only deserializing part of the response HttpClient ReadAsAsync <Type>仅反序列化响应的一部分

I have also tried (was using class Bulkv1Job before I used xsd to convert the xml to a class) 我也尝试过(在使用xsd将xml转换为类之前使用过Bulkv1Job类)

[DataContract]
public class Bulkv1Job
{
    [DataMember]
    string id { get; set; }
    [DataMember]
    string operation { get; set; }
    [DataMember]
    string @object { get; set; }
    ...
}

and

[XmlRoot("jobInfo")]
public class Bulkv1Job
{
    [XmlElement("id")]
    string id { get; set; }
    [XmlElement("operation")]
    string operation { get; set; }
    ...
}

Hmmm I'm not an expert with soap but it should have decorators like [DataMember] on your properties and [DataContract(NameSpace="jobInfo")] on your class if I remember well. 嗯,我不是肥皂专家,但如果我记得很好的话,应该在属性上使用[DataMember]这样的修饰符,在类上使用[DataContract(NameSpace =“ jobInfo”))这样的修饰符。 You can see that in the first suggestion you provide the guy use [XmlRoot] and [XmlElement] 您可以看到,在第一个建议中,您提供给该人使用[XmlRoot]和[XmlElement]

You can also see WCF Datacontract, some fields do not deserialize , maybe it would help you 您还可以看到WCF Datacontract,某些字段未反序列化 ,也许会对您有所帮助

After testing with 经过测试

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;
}

I found that the serializer failed on the above line due to a class protection error. 我发现序列化程序由于类保护错误而在上一行失败。 Ensuring the jobInfo class was public and accessible, the error went away and the deserialize(stream) worked. 确保jobInfo类是公共的且可访问的,错误消失并且deserialize(stream)工作。

Removing that code and using readAsAsync<jobInfo>(...) worked appropriately afterwards. 之后,删除该代码并使用readAsAsync<jobInfo>(...)工作。

Thanks @Ryan 谢谢@Ryan

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReadAsAsync Json反序列化 - ReadAsAsync Json Deserialization ReadAsAsync 调用 WebAPI 不会将 json 重构为类 - ReadAsAsync calling a WebAPI not reconstituting json to class 使用 HttpContent.ReadAsAsync 时代码停止 - Code stops when using HttpContent.ReadAsAsync 使用 YamlDotNet 将字符串嵌套到类反序列化 - Nested string to class deserialization using YamlDotNet ReadAsAsync 转换自定义 class 返回 null 用于 .net 核心 - ReadAsAsync cast custom class return null for .net core 使用自定义XmlMediaTypeFormatter删除Web API响应c#.net中的所有名称空间 - Using custom XmlMediaTypeFormatter to remove all namespaces in web api response c# .net ReadAsAsync - 错误:“Type是一个接口或抽象类,无法实例化。” - ReadAsAsync - Error : “Type is an interface or abstract class and cannot be instantiated.” ProtoContract破坏XmlMediaTypeFormatter行为 - ProtoContract breaks XmlMediaTypeFormatter behavior 无法使用ReadAsAsync反序列化XML响应中的列表<T> - Unable to deserialize list in a XML Response using ReadAsAsync<T> 使用 HttpContent.ReadAsAsync<t> 使用一个 object 或数组解析响应</t> - Using HttpContent.ReadAsAsync<T> to parse responses with one object or an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM