【问题标题】:Consuming Yahoo PlaceFinder JSON in C# using WebRequest使用 WebRequest 在 C# 中使用 Yahoo PlaceFinder JSON
【发布时间】:2012-06-24 11:21:05
【问题描述】:

我想我会在这里发布这个问题,而不是一个问题,而是与社区分享我在 StackOverflow 上找不到答案后编写的一些代码。如果有人想看一下代码并改进它,那会很好,但不是必需的。我省略了一些代码(try-catch 块和错误处理),以便更容易使用概念和代码。

【问题讨论】:

    标签: c# json httpwebrequest yahoo jsonserializer


    【解决方案1】:

    那么,让我们从我需要解决的问题开始。我希望能够允许某人输入城市、州、邮政编码组合的部分或全部,并使用Yahoo's PlaceFinder API 来确定它的确切位置。没什么特别的,只是一种从邮政编码解析城市和州的简单方法,反之亦然。

    这个过程涉及:

    1. 在服务器端接收输入(城市/州/邮编)
    2. 使用适当的参数构造一个 URL(我想接收 JSON 格式的响应)
    3. 向 PlaceFinder 服务发出 HTTP GET 请求。
    4. 使用 JSON 响应的方式可以为我提供 C# 中的对象模型,以便轻松处理响应数据。

    让我们从您要导入的命名空间开始:

    using System.Net; // for HttpWebRequest
    using System.Text; // for utf8 encoding
    using System.Web.Script.Serialization; // for json parsing
    using System.IO; // for datastream
    

    接下来,我们来看看构造请求:

    string parameters = String.Empty;
    UTF8Encoding utf8 = new UTF8Encoding(); // yahoo docs state utf-8 encoding
    string unparsedLocation = "Beverly Hills, CA 90210"; // contrived example
    
    parameters += "line2=" + Url.Encode(unparsedLocation); // yahoo docs say to url encode
    parameters += "&flags=J"; // J = want the response formatted in json
    parameters += "&appid=[your-app-id-here]"; // using your appID obtained from Yahoo
    parameters = utf8.GetString(utf8.GetBytes(parameters));
    WebRequest request = WebRequest.Create(@"http://where.yahooapis.com/geocode?" + parameters);
    request.Method = "GET";
    

    接下来,我们想要获取响应并将其放入一个易于使用的对象模型中:

    WebResponse response = request.GetResponse();
    // Check the status. If it's not OK then don't bother with trying to parse the result
    if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
    {
        // Get the stream containing content returned by the server.
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
    
        JavaScriptSerializer jss = new JavaScriptSerializer();
        YahooResponse yr = jss.Deserialize<YahooResponse>(responseFromServer);
    
        // You may not want such strict checking; if not, remove the "NO ERROR" check
        if (yr.ResultSet.Error == 0 && yr.ResultSet.ErrorMessage.ToUpper() == "NO ERROR" && yr.ResultSet.Found > 0)
        {
            // inside here is where you can do whatever you need to.
            // ex. 1 - get the first result
            Result result = yr.ResultSet.results[0];
    
            // ex. 2 - loop through results
            foreach (Result r in yr.ResultSet.results)
            {
                // add values to a List<T> or something useful
            }
        }
    }
    
    // always do this as a matter of good practice
    response.Close();
    

    但是等等,还有最后一个重要的部分丢失了。什么是“YahooResponse”对象?类定义是什么样的?这是我想出的:

    namespace PlaceFinder
    {
        public class YahooResponse
        {
            public ResultSet ResultSet { get; set; }
        }
    
        public class ResultSet
        {
            public string version { get; set; }
            public int Error { get; set; }
            public string ErrorMessage { get; set; }
            public string Locale { get; set; }
            public int Quality { get; set; }
            public int Found { get; set; }
            public Result[] results { get; set; }
        }
    
        public class Result
        {
            public int quality { get; set; }
            public string latitude { get; set; }
            public string longitude { get; set; }
            public string offsetlat { get; set; }
            public string offsetlon { get; set; }
            public int radius { get; set; }
            public string name { get; set; }
            public string line1 { get; set; }
            public string line2 { get; set; }
            public string line3 { get; set; }
            public string line4 { get; set; }
            public string house { get; set; }
            public string street { get; set; }
            public string xstreet { get; set; }
            public string unittype { get; set; }
            public string unit { get; set; }
            public string postal { get; set; }
            public string neighborhood { get; set; }
            public string city { get; set; }
            public string county { get; set; }
            public string state { get; set; }
            public string country { get; set; }
            public string countrycode { get; set; }
            public string statecode { get; set; }
            public string countycode { get; set; }
            public string uzip { get; set; }
            public string hash { get; set; }
            public long woeid { get; set; }
            public int woetype { get; set; }
        }
    }
    

    在此处了解有关 PlaceFinder 服务的更多信息:http://developer.yahoo.com/geo/placefinder/guide/

    【讨论】:

      【解决方案2】:

      幸运的是,有人为此在 GIT 上编写了一个包装器。这是链接:https://github.com/danludwig/NGeo。它也可以通过 NuGet 获得。对我来说非常方便!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-13
        • 2011-05-08
        相关资源
        最近更新 更多