【发布时间】:2016-12-20 20:56:39
【问题描述】:
我明白了
“无法将当前的JSON数组(如[1,2,3])反序列化为类型'',因为该类型需要一个JSON对象(如{“name”:“value”})才能正确反序列化”错误
我浏览了大多数类似的问题,但没有找到我要寻找的答案,所以我要问一个新问题。
这是我的 JSON:
{
"coord": {
"lon": 105.84,
"lat": 21.59
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"base": "stations",
"main": {
"temp": 20.31,
"pressure": 1010.36,
"humidity": 98,
"temp_min": 20.31,
"temp_max": 20.31,
"sea_level": 1026.71,
"grnd_level": 1010.36
},
"wind": {
"speed": 1.86,
"deg": 124.5
},
"rain": {
"3h": 0.3075
},
"clouds": {
"all": 92
},
"dt": 1482264413,
"sys": {
"message": 0.0114,
"country": "VN",
"sunrise": 1482190209,
"sunset": 1482229157
},
"id": 1566319,
"name": "Thai Nguyen",
"cod": 200
}
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
string url = "http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid={MyAppID}";
HttpWebRequest httpWebRequset = (HttpWebRequest)WebRequest.Create(url);
httpWebRequset.Method = WebRequestMethods.Http.Get;
httpWebRequset.ContentType = "application/json";
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequset.GetResponse();
using (var StreamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseString = StreamReader.ReadToEnd();
ResponseData data = JsonConvert.DeserializeObject<ResponseData>(responseString);
ShowTemp.Text = data.main.temp + "°C";
ShowWheater.Text = data.weather.description;
}
}
当我尝试获取温度时,我可以找到它,但是当我想从以下位置获取描述时:
{
...
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
]
...
}
我得到了错误。
【问题讨论】:
-
显示您的
ResponseData课程。 -
ResponseData 类是什么样的?我怀疑它需要一个格式为'{“id”:500,“main”:“Rain”,“description”:“light rain”,“icon”:“10n”}'的天气对象。您尝试解析为天气对象的方括号表示它正在尝试读取对象数组。
-
确实,在此类的根对象中,您可能需要类似
public List<Weather> weather {get;set;}的内容,其中Weather是具有id和description等属性的类。 -
这是我的 responseData 类 ResponseData { public Main main;公共天气天气; } 类主 { 公共字符串临时; } 公共类天气 { 公共字符串描述; }