RestSharp XML 反序列化为列表 [英] RestSharp XML Deserialization into List

查看:52
本文介绍了RestSharp XML 反序列化为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 RestSharp 反序列化以下 xml,但我总是得到一个空元素列表.我是基于 REST 的服务的新手,需要一些专家帮助!=)

I am trying to deserialize the following xml using RestSharp, but I always get a list of null elements. I am new to REST based services and need some expert help! =)

找到解决方案:我想通了.您必须明确告诉 RestSharp 正在反序列化的数据类型:

Solution Found: I figured it out. You have to explicitly tell RestSharp what kind of data is being deserialized:

request.OnBeforeDeserialization = resp => {
                resp.ContentType = "application/json";
            };

完整 XML:http://autocomplete.wunderground.com/aq?query=San%20F&format=xml一些 XML 如下:

Full XML: http://autocomplete.wunderground.com/aq?query=San%20F&format=xml Some of the XML is below:

<RESULTS>
<name>San Francisco, California</name>
<type>city</type>
<c>US</c>
<zmw>94101.1.99999</zmw>
<tz>America/Los_Angeles</tz>
<tzs>PDT</tzs>
<l>/q/zmw:94101.1.99999</l>
</RESULTS>

这是我的 XMLResults 类:

Here is my XMLResults class:

public class XMLResults
{
    public List<name> names {get; set;}
}
public class name 
{
    public string city {get; set;}
}

这是我的 getWeather 方法:

And here is my getWeather method:

public void getWeather(string query)
{
    var client = new RestClient ();
    var request = new RestRequest(Method.GET);
    client.BaseUrl = "http://autocomplete.wunderground.com";
    request.Resource = "aq";
    request.AddParameter ("query", query);
    request.AddParameter ("format", "xml");
    request.RequestFormat = DataFormat.Xml;
    var city = client.Execute<XMLResults>(request);
    Console.WriteLine (city.Data.names.Count); // Results in 20

}           

推荐答案

我必须明确告诉 RestSharp 正在反序列化的数据类型:request.OnBeforeDeserialization = resp =>{ resp.ContentType = "application/json";};

I had to explicitly tell RestSharp what kind of data is being deserialized: request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json";};

这篇关于RestSharp XML 反序列化为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆