C# 获取天气 JSON解析

来源:互联网 发布:汤姆索亚历险记 知乎 编辑:程序博客网 时间:2024/05/01 20:13

说明:

winform获取中国天气的数据

中国天气返回的是JSON数据格式,这里做简单的解析。

用的http://www.weather.com.cn/data/sk/101010100.html获取的天气。    【101010100为城市代码参见      接口详解】

命名空间:

由于C#不是asp.net,所以要在项目中要先添加两个命名空间的引用。(流年⌒在等谁的问问回答)
1:System.Web;
2:System.Web.Extensions;



然后在项目中添加命名空间引用,如下
using System.Web.Script.Serialization;



程序:

关键代码如下:

using System.Web;using System.Web.Extensions;using System.Web.Script.Serialization;
类,装天气信息public class Weather{    public Info weatherinfo;}public class Info{    public string city;//城市    public int temp;   //温度    public string WD;  //风向    public string WS;     //风力    public string SD;  //相对湿度    public string time;//更新时间}
//获取天气和解析HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.weather.com.cn/data/sk/101010100.html");request.Timeout = 5000;request.Method = "GET";HttpWebResponse response = (HttpWebResponse)request.GetResponse();StreamReader sr = new StreamReader(response.GetResponseStream());string jsonstr = sr.ReadLine();JavaScriptSerializer j = new JavaScriptSerializer();Weather weather = new Weather();weather = j.Deserialize<Weather>(jsonstr);



结果:



参考资料:


C#实现JSON序列化与反序列化介绍:http://www.csharpwin.com/csharpspace/10822r2908.shtml

通过代码打开一个网站,并获取该网站输出的字符串:http://bbs.csdn.net/topics/300168123  wangjun8868 的回帖

JSON介绍:http://baike.baidu.com/view/136475.htm

JSON的命名空间引用:http://wenwen.soso.com/z/q360338444.htm

其他:

http://www.soaspx.com/dotnet/csharp/csharp_20100713_5052.html

http://www.cnblogs.com/txw1958/archive/2012/08/01/csharp-json.html

天气预报接口:http://blog.csdn.net/a535537066/article/details/6656365

http://www.weather.com.cn/data/sk/101010100.html 

http://www.weather.com.cn/data/cityinfo/101010100.html

http://m.weather.com.cn/data/101010100.html