【问题标题】:How to get a specific part of the data from a rest webservice responce?如何从 REST Web 服务响应中获取特定部分的数据?
【发布时间】:2014-11-05 20:52:04
【问题描述】:

我是 REST Web 服务的新手,我尝试了解如何使用它们。

我在 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 天气网络服务获取 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;
        }

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

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

请帮帮我。

【问题讨论】:

    标签: c# xml web-services rest


    【解决方案1】:

    你的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");
    

    【讨论】:

      【解决方案2】:

      您可以使用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;
      }
      

      【讨论】:

      • This will help you to avoid parsing errors if scheme of returned object be changed 假设lon 更改为long。这会运行jsonResult.coord.lon 吗?我的回答也有同样的问题。 (顺便说一句,您不需要&lt;ExpandoObject&gt;ExpandoObjectConverter,您可以安全地将JsonConvert.DeserializeObject 转换为动态
      • 但如果我只使用lon 属性,其他人的任何更改都不会影响代码。而且我不需要在代码中保留完整的方案。
      • Json.Net 的优点在于,如果属性名称更改或某些对象消失,旧结构将具有 null(默认)值。所以我仍然认为没有问题。承认吧。在我使用mode=json 发布该链接之前,您一无所知您可能仍想更改答案并解析 xml :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多