zoukankan      html  css  js  c++  java
  • C# 获取天气 JSON解析

    说明:

    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;



    程序:

    关键代码如下:

    [csharp] view plain copy
    1. using System.Web;  
    2. using System.Web.Extensions;  
    3. using System.Web.Script.Serialization;  
    [csharp] view plain copy
    1. 类,装天气信息  
    2. public class Weather  
    3. {  
    4.     public Info weatherinfo;  
    5. }  
    6. public class Info  
    7. {  
    8.     public string city;//城市  
    9.     public int temp;   //温度  
    10.     public string WD;  //风向  
    11.     public string WS;     //风力  
    12.     public string SD;  //相对湿度  
    13.     public string time;//更新时间  
    14. }  
    [csharp] view plain copy
    1. //获取天气和解析  
    2. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.weather.com.cn/data/sk/101010100.html");  
    3. request.Timeout = 5000;  
    4. request.Method = "GET";  
    5. HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
    6. StreamReader sr = new StreamReader(response.GetResponseStream());  
    7. string jsonstr = sr.ReadLine();  
    8. JavaScriptSerializer j = new JavaScriptSerializer();  
    9. Weather weather = new Weather();  
    10. 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

  • 相关阅读:
    webpack特点,安装,兼容性
    我们为什么需要构建工具
    vue-router keep-alive
    Es6模块化
    AMD-require.js
    CommonJs
    OJ
    算法
    flex属性 flex-grow、flex-shrink、flex-basic
    js过滤数组中的空值
  • 原文地址:https://www.cnblogs.com/alan666/p/8312355.html
Copyright © 2011-2022 走看看