在MIS系统开发中,有时需要在主页顶部显示天气信息,本篇经验将和大家介绍一下实现过程。
1、一个可以获取各个城市天气预报情况的网站:
http://wthrcdn.etouch.cn/weather_mini?city=合肥
参数city的值根据你所在的城市相应修改,获取到的气象信息如下图所示:
JSON字符串如下:
{
"desc": "OK",
"status": 1000,
"data": {
"wendu": "25",
"ganmao": "各项气象条件适宜,无明显降温过程,发生感冒机率较低。",
"forecast": [
{
"fengxiang": "南风",
"fengli": "3-4级",
"high": "高温 27℃",
"type": "晴",
"low": "低温 15℃",
"date": "14日星期五"
},
{
"fengxiang": "东风",
"fengli": "微风级",
"high": "高温 28℃",
"type": "多云",
"low": "低温 18℃",
"date": "15日星期六"
},
{
"fengxiang": "东南风",
"fengli": "3-4级",
"high": "高温 25℃",
"type": "中雨",
"low": "低温 16℃",
"date": "16日星期天"
},
{
"fengxiang": "西风",
"fengli": "3-4级",
"high": "高温 25℃",
"type": "多云",
"low": "低温 20℃",
"date": "17日星期一"
},
{
"fengxiang": "西北风",
"fengli": "3-4级",
"high": "高温 27℃",
"type": "晴",
"low": "低温 15℃",
"date": "18日星期二"
}
],
"yesterday": {
"fl": "3-4级",
"fx": "南风",
"high": "高温 24℃",
"type": "晴",
"low": "低温 13℃",
"date": "13日星期四"
},
"aqi": "73",
"city": "合肥"
}
}
附一个可以用于验证JSON字符串正确性的网址:http://www.bejson.com/
2、打开json2csharp网站,网站网址为:http://json2csharp.com/,将以上JSON串复制到编辑框中,然后点击“Generate”按钮,生成实体类,如下图所示:
3、C#代码实现,核心代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CommonClass
{
public class Forecast
{
public string fengxiang { get; set; }
public string fengli { get; set; }
public string high { get; set; }
public string type { get; set; }
public string low { get; set; }
public string date { get; set; }
}
public class Yesterday
{
public string fl { get; set; }
public string fx { get; set; }
public string high { get; set; }
public string type { get; set; }
public string low { get; set; }
public string date { get; set; }
}
public class Data
{
public string wendu { get; set; }
public string ganmao { get; set; }
public List<Forecast> forecast { get; set; }
public Yesterday yesterday { get; set; }
public string aqi { get; set; }
public string city { get; set; }
}
public class RootObject
{
public string desc { get; set; }
public int status { get; set; }
public Data data { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
namespace CommonClass
{
public class Json2Entities
{
/// <summary>
/// 将json字符串转化为方法实体类
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T JsonToObject<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T jsonObject = (T)ser.ReadObject(ms);
ms.Close();
return jsonObject;
}
}
}
//用UTF-8转码有汉字参数的url
protected string UrlUtf_8(string url)
{
byte[] bs = Encoding.GetEncoding("UTF-8").GetBytes(url);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bs.Length; i++)
{
if (bs[i] < 128)
sb.Append((char)bs[i]);
else
{
sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0'));
sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0'));
}
}
return sb.ToString();
}
//用UrlGB2312转码有汉字参数的url
protected string UrlGB2312(string url)
{
byte[] bs = Encoding.GetEncoding("GB2312").GetBytes(url);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bs.Length; i++)
{
if (bs[i] < 128)
sb.Append((char)bs[i]);
else
{
sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0'));
sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0'));
}
}
return sb.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public string GetFunction(string url)
{
string serviceAddress = url;
//HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "text/html;charset=UTF-8";
request.Method = "GET";
//通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容
Stream myResponseStream = response.GetResponseStream();
//站点在响应的时候用gzip压缩过了,用using (var gStream = new GZipStream(myResponseStream, CompressionMode.Decompress)){}解压
using (var gStream = new GZipStream(myResponseStream, CompressionMode.Decompress))
{
//Encoding.GetEncoding("UTF-8")转码
StreamReader myStreamReader = new StreamReader(gStream, Encoding.GetEncoding("UTF-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
response.Close();
myResponseStream.Close();
return retString;
}
}
string url = "http://wthrcdn.etouch.cn/weather_mini?city=合肥";
string info = GetFunction(url);
RootObject rootObj = new RootObject();
rootObj = Json2Entities.JsonToObject<RootObject>(info);
string weather = rootObj.data.city + " " + rootObj.data.forecast[0].type + " " + rootObj.data.forecast[0].low.Replace("低温", "") + " ~ " + rootObj.data.forecast[0].high.Replace("高温", "");
4、实现效果如下图所示: