如何从休息Web服务响应中获取特定部分数据?

时间:2014-11-05 20:52:04

标签: c# xml web-services rest

我是休息网络服务的新手,我试着了解如何使用它们。

我在C#中定义一个http get请求,如下所示:

static string HttpGet(string url)
        {
            HttpWebRequest req = WebRequest.Create(url)
                                 as HttpWebRequest;
            string result = null;
            using (HttpWebResponse resp = req.GetResponse()
                                          as HttpWebResponse)
            {
                StreamReader reader =
                    new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            return result;
        }

然后我在一个按钮中使用HttpGet从THIS天气webservice获取xml数据(我把txtOut用于查找我的代码是否正常工作)。

private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            string test = HttpGet("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");

            txtOut.Text = test;
        }

将整个xml从发送get请求发送到该url: http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml

所以我的问题是如何在变量中保存该xml的特定部分?像卡尔文的最低温度,所以我可以将其转换为华氏温度或摄氏温度。

请帮助我。

2 个答案:

答案 0 :(得分:7)

你api也会返回json,所以你可以像下面一样使用它(使用Json.Net

using (WebClient wc = new Webclient())
{
    var json = wc.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London&mode=json");
    var obj = JsonConvert.DeserializeObject<OpenWeatherMap.Root>(json);
}

public class OpenWeatherMap
{
    public class Coord
    {
        public double lon { get; set; }
        public double lat { get; set; }
    }

    public class Sys
    {
        public int type { get; set; }
        public int id { get; set; }
        public double message { get; set; }
        public string country { get; set; }
        public int sunrise { get; set; }
        public int sunset { get; set; }
    }

    public class Weather
    {
        public int id { get; set; }
        public string main { get; set; }
        public string description { get; set; }
        public string icon { get; set; }
    }

    public class Main
    {
        public double temp { get; set; }
        public int humidity { get; set; }
        public double pressure { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }

    public class Wind
    {
        public double speed { get; set; }
        public double gust { get; set; }
        public int deg { get; set; }
    }



    public class Clouds
    {
        public int all { get; set; }
    }

    public class Root
    {
        public Coord coord { get; set; }
        public Sys sys { get; set; }
        public List<Weather> weather { get; set; }
        public string @base { get; set; }
        public Main main { get; set; }
        public Wind wind { get; set; }
        public Dictionary<string,double> rain { get; set; }
        public Clouds clouds { get; set; }
        public int dt { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public int cod { get; set; }
    }
}

如果您坚持使用xml,那么您可以使用Linq2Xml + XPath

var xDoc = XDocument.Load("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");

var windSpeed  = (double)xDoc.XPathSelectElement("//wind/speed").Attribute("value");

var temp = (double)xDoc.Root.Element("temperature").Attribute("value");

答案 1 :(得分:1)

你可以使用Newtonsoft.Json json converot获得json响应并转换为动态obj,或者我相信任何其他可以将json转换为动态的转换器。 这将帮助您避免在更改返回对象的方案时解析错误。

using (WebClient wc = new Webclient())
{
    var json = wc.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=London&mode=json");
    dynamic jsonResult = JsonConvert.DeserializeObject<ExpandoObject>(json , new ExpandoObjectConverter());

    // using dynamic object 
    var lon = jsonResult.coord.lon;
}