0

如何从 api 代码隐藏文件中获取国家/地区名称,以便我可以使用它在 gridview 中显示?

foreach (var i in data)
string country = "http://www.geoplugin.net/json.gp?ip=xx.xx.xx.xx"
country=country+"i.ip";
i.Country = country;
4

1 回答 1

2

创建一个包含来自http://www.geoplugin.net/json.gp作为字符串属性的键的类。最小值如下所示:

   public class GeoPlugin
    {
        public String geoplugin_countryName { get; set; }
    }

执行 HttpWebRequest 并将 JSON 响应反序列化为您创建的类并访问 country 属性:

String url = String.Format("http://www.geoplugin.net/json.gp?ip={0}", "173.194.112.31");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json";
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
   JavaScriptSerializer jss = new JavaScriptSerializer();
   var result = jss.Deserialize<GeoPlugin>(streamReader.ReadToEnd());
   i.Country = result.geoplugin_countryName;
}

要使用JavaScriptSerializer,您需要参考System.Web.Extensions(4.0 版)而不是使用 .net 4.0 客户端配置文件。

于 2013-09-14T08:38:12.060 回答