如何从api codebehind文件获取国家/地区名称,以便我可以使用它在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;
答案 0 :(得分:2)
创建一个包含来自http://www.geoplugin.net/json.gp的键作为String属性的类。最小值如下:
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客户端配置文件。