日期:2014-05-18  浏览次数:20873 次

关于,调用api,返回的json值
我有这样一个api
http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=115.60.192.117

我在C#中这样写的代码。
C# code
WebRequest request = WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=115.60.192.117");
        
        WebResponse response = request.GetResponse();
        Stream stream = response.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string str = reader.ReadLine();
        Response.Write(str);


输出的:var remote_ip_info = {"ret":1,"start":"115.60.0.0","end":"115.61.78.255","country":"\u4e2d\u56fd","province":"\u6cb3\u5357","city":"\u90d1\u5dde","district":"","isp":"\u8054\u901a","type":"","desc":""}; 


这已经是字符串了。我怎么得到city的值?
方法1:如果是截取的话,我会。
方法2:有没有其他的什么方法?或者好的解决代码

------解决方案--------------------
WebRequest request = WebRequest.Create("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=115.60.192.117");

WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string js = reader.ReadLine();

js = js.Replace("var remote_ip_info = ", "").Trim().TrimEnd(';');

var z = (Dictionary<string, string>)new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(js, typeof(Dictionary<string, string>));
foreach (KeyValuePair<String, String> s in z)
{
if (s.Key == "city")
MessageBox.Show(s.Value);
}

引用
System.Web.Extensions.dll 
并且需要.net 3.5以上版本
------解决方案--------------------
还有一种方式是使用正则表达式匹配字符串...