简体   繁体   English

将HttpResponseMessage转换为XML到Object

[英]Convert HttpResponseMessage To XML to Object

I have defined the Serialization for my Object idAssignmentResult . 我已经为我的对象idAssignmentResult定义了序列化。 But how do I convert an HttpResponseMessage that IS XML, to it's class? 但是,如何将IS XML的HttpResponseMessage转换为它的类? I am getting an error: 我收到一个错误:

Value of type 'System.Net.Http.HttpContent' cannot be converted to 'System.Xml.XmlReader' “System.Net.Http.HttpContent”类型的值无法转换为“System.Xml.XmlReader”

I will do both vb.net and c# 我会做vb.net和c#

vb.net vb.net

    Dim response As New HttpResponseMessage()
        Try
            Using client As New HttpClient()
                Dim request As New HttpRequestMessage(HttpMethod.Post, "url")
                request.Content = New StringContent(stringWriter.ToString, Encoding.UTF8, "application/xml")

                response = client.SendAsync(request).Result
            End Using
        Catch ex As Exception
            lblerror.Text = ex.Message.ToString
        End Try
    Dim responseString = response.Content

    Dim xmls As New XmlSerializer(GetType(idAssignmentResult))
    Dim assignmentResult As New idAssignmentResult()
    xmls.Deserialize(responseString, assignmentResult) /// cannot convert HttpContent to XmlReader

c# C#

    StringWriter stringWriter = new StringWriter();
    XmlSerializer serializer = new XmlSerializer(typeof(personV3R));
    personV3R person = new personV3R(); serializer.Serialize(stringWriter, person);
    HttpResponseMessage response = new HttpResponseMessage();
    try
    {
        using (HttpClient client = new HttpClient())
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "url");
            request.Content = new StringContent(stringWriter.ToString, Encoding.UTF8, "application/xml");
            response = client.SendAsync(request).Result;
        }
    }
    catch (Exception ex)
    {
        lblerror.Text = ex.Message.ToString;
    }

    var responseString = response.Content;

    XmlSerializer xmls = new XmlSerializer(typeof(idAssignmentResult));
    idAssignmentResult assignmentResult = new idAssignmentResult();
    xmls.Deserialize(responseString, assignmentResult);

You shoud do it as 你应该这样做

1. 1。

var responseString = await response.Content.ReadAsStringAsync();

2. 2。

var assignmentResult = 
             (idAssignmentResult)xmls.Deserialize(new StringReader(responseString));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM