c#将HttpResponseMessage反序列化为对象

本文关键字:对象 反序列化 HttpResponseMessage | 更新日期: 2023-09-27 18:10:11

我在将HttpResponseMessage反序列化为对象时遇到了一些问题。问题是,当对象应该反序列化所有字段为空时,不会抛出异常。

HttpContent content = new StringContent(xml);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/xml");
HttpResponseMessage response = await client.PostAsync("URL", content).ConfigureAwait(false);
// Parse response
if (response.IsSuccessStatusCode)
{
    XmlSerializer serializer = new XmlSerializer(typeof(ResponseObject));
    Stream responseStream = await response.Content.ReadAsStreamAsync();
    ResponseObject responseObject = serializer.Deserialize(responseStream) as ResponseObject;
    //Possible example of wrong data
    Console.WriteLine(responseObject.Message);
}
[XmlRoot("response")]
public class ResponseObject
{
    [XmlElement("session")]
    public string Session { get; set; }
    [XmlElement("status")]
    public string Status { get; set; }
    [XmlElement("message")]
    public string Message { get; set; }
}

作为字符串的响应消息

"<?xml version='"1.0'" encoding='"ISO-8859-1'"?>
<response>
    <val n='"session'">SESSION ID</val>
    <val n='"status'">201</val>
    <val n='"message'">Created</val>
</response>"
我错过什么了吗?我对序列化/反序列化还是个新手。感谢你的指点

c#将HttpResponseMessage反序列化为对象

好的,我在Eser和Biscuits的帮助下解决了这个问题。

我试图重用代码,并没有真正考虑到响应消息具有与早期项目不同的结构。

我把我的ResponseObject改成了:

[XmlRoot("response")]
public abstract class ResponseObject
{
    [XmlIgnore]
    public bool Success { get; set; }
    [XmlIgnore]
    public string Session
    {
        get
        {
            var result = Values.FirstOrDefault(n => n.Name == "session");
            return result.Value;
        }
    }
    [XmlIgnore]
    public string Status
    {
        get
        {
            var result = Values.FirstOrDefault(n => n.Name == "status");
            return result.Value;
        }
    }
    [XmlIgnore]
    public string Message
    {
        get
        {
            var result = Values.FirstOrDefault(n => n.Name == "message");
            return result.Value;
        }
    }
    [XmlElement("val")]
    public List<ResponseXmlWrapper<string>> Values;
}
public class ResponseXmlWrapper<T>
{
    [XmlAttribute("n")]
    [JsonProperty("n")]
    public string Name { get; set; }
    [XmlText]
    [JsonProperty()]
    public T Value { get; set; }
    public ResponseXmlWrapper()
    {
    }
    public ResponseXmlWrapper(string attributeName, T value)
    {
        Name = attributeName;
        Value = value;
    }
}

我不知道这是不是一个最优的解决方案,但它是有效的。