RestSharp XML Deserialization into List

2019-09-13 15:23发布

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

}           

2条回答
地球回转人心会变
2楼-- · 2019-09-13 15:45

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

查看更多
虎瘦雄心在
3楼-- · 2019-09-13 15:58

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.

查看更多
登录 后发表回答