RestSharp XML Deserialization into List

陌路散爱 提交于 2019-12-11 21:19:45

问题


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! =)

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

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>

Here is my XMLResults class:

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

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

}           

回答1:


If it were me I would take a valid XML response ( like the one you posted ) and create a class from it using the xsd.exe program that comes with Visual Studio (it is VS Command Line Tool)

Generate C# class from XML

Then you can easily Serialize and Deserialize your Object.




回答2:


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



来源:https://stackoverflow.com/questions/18881344/restsharp-xml-deserialization-into-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!