- namespace TestAPI
- {
- public class data
- {
- public test weatherinfo { get; set; }
- }
- }
- namespace TestAPI
- {
- public class test
- {
- public string city { get; set; }
- public string cityid { get; set; }
- public string temp { get; set; }
- public string WD { get; set; }
- public string WS { get; set; }
- public string SD { get; set; }
- public string AP { get; set; }
- public string njd { get; set; }
- public string WSE { get; set; }
- public string time { get; set; }
- public string sm { get; set; }
- public string isRadar { get; set; }
- public string Radar { get; set; }
- }
- }
- namespace TestAPI
- {
- public partial class webForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- data t = new TestAPI.data();
- t = JsonConvert.DeserializeObject(str());
- String AP = t.weatherinfo.AP;
- Response.Write(JsonConvert.SerializeObject(t));
- //string tianqiJieshou = "{\"weatherinfo\":{\"city\":\" 北京 \",\"cityid\":\"101010100\",\"temp\":\"27.9\",\"WD\":\" 南风 \",\"WS\":\" 小于 3 级 \",\"SD\":\"28%\",\"AP\":\"1002hPa\",\"njd\":\" 暂无实况 \",\"WSE\":\"<3\",\"time\":\"17:55\",\"sm\":\"2.1\",\"isRadar\":\"1\",\"Radar\":\"JC_RADAR_AZ9010_JB\"}}";
- // 首先创建一个天气的模型接受 city 之后的数据
- // 创建一个名字为 weatherinfo 的字段, 接受这些信息
- //test tianqi = new test();
- //t.weatherinfo = tianqi;
- //tianqi.AP = "1";
- //tianqi.city = "10010";
- //string ssa = JsonConvert.SerializeObject(t);
- //string aaa = "";
- }
- private string str()
- {
- string str = "";
string URL = "http://www.weather.com.cn/data/sk/" + (int)city. 北京 + ".html";
- HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URL);
- req.Method = "Get";
- using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
- {
- StreamReader sw = new StreamReader(rsp.GetResponseStream());
- str = sw.ReadToEnd();
- return str;
- }
- }
- }
- public enum city
- {
北京 = 101010100,
海淀 = 101010200,
朝阳 = 101010300,
顺义 = 101010400,
怀柔 = 101010500,
通州 = 101010600,
昌平 = 101010700,
延庆 = 101010800,
丰台 = 101010900,
石景山 = 101011000,
大兴 = 101011100
}
}
利用 Newtonsoft.JSON 序列化反序列化.
天气 API 返回的数据存在了 Test 模型中, 然后使用
HttpWebReques 接受 API 中数据,
使用 JsonConvert.DeserializeObject 反序列化
使用 JsonConvert.SerializeObject 序列化
另 City 类转自一位博友的, 在回头找就找不到了, 一脸尴尬
来源: http://www.bubuko.com/infodetail-2801792.html