获取天气数据C#
利用HttpClient的GetAsync方法
class GetJson
{
private string APIStr = "http://t.weather.sojson.com/api/weather/city/101030100";
public async Task<string> HttpGet()
{
Uri APIUri = new Uri(APIStr);
string data = null;
try
{
using (HttpClient httpClient = new HttpClient())
{
TimeSpan timeOut = new TimeSpan(0, 0, 30);
httpClient.Timeout = timeOut;
httpClient.DefaultRequestHeaders.Accept.Clear();
data = await httpClient.GetStringAsync(APIUri);
}
}
catch(ArgumentOutOfRangeException e)
{
return e.Message.ToString();
}
return data;
}
}
- json数据的转化为本地对象
- 引入处理json的package:Newtonsoft.Json
- 建立包含json相同数据相同的属性类
public class JsonInfo
{
public DateTime time { get; set; }
public CityInfo cityinfo { get; set; }
public string date { get; set; }
public string message { get; set; }
public string status { get; set; }
public Data data { get; set; }
}
#region 详细数据
public class CityInfo
{
public string city { get; set; }
public string cityId { get; set; }
public string parent { get; set; }
public string upadataTime { get; set; }
}
public class Data
{
public string shidu { get; set; }
public string pm25 { get; set; }
public string pm10 { get; set; }
public string quality { get; set; }
public string wendu { get; set; }
public string ganmao { get; set; }
public WeatherData yesterday { get; set; }
public List<WeatherData> forecast { get; set; }
}
public class WeatherData
{
public string date { get; set; }
public string sunrise { get; set; }
public string high { get; set; }
public string low { get; set; }
public string aqi { get; set; }
public DateTime ymd { get; set; }
public string week { get; set; }
public string fx { get; set; }
public string fl { get; set; }
public string type { get; set; }
public string notice { get; set; }
}
#endregion
- 转化成对象:
public class JsonStrDel
{
public JsonInfo WeatherMessage;
public void DataDel(string jsonMessage )
{
WeatherMessage=JsonConvert.DeserializeObject<JsonInfo>(jsonMessage);
}
}