我得到了
"无法将当前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"
}
]
...
}
我收到了错误。
答案 0 :(得分:2)
JSON包含一个Weather
数组,即使它只有一个条目。这用方括号表示,见下文:
“天气”: [ { “ID”:500, “主”:“雨”, “描述”:“小雨”, “图标”: “10N” } 的 强>
你说这是你的ResponseData
课程:
class ResponseData
{
public Main main;
public Weather weather;
}
class Main
{
public string temp;
}
class Weather
{
public string description;
}
将ResponseData
类更改为:
public class ResponseData
{
public Main main { get; set; }
public List<Weather> weather { get; set; } // This is a List<T> of Weather
} // It can contain more than one entry
// for weather
public class Main
{
public double temp { get; set; } // This is a double
}
public class Weather
{
public string description { get; set; }
}
您还必须引用添加到项目中的System.Collections
以及相关的using
:
using System.Collections;
由于天气现在是一个列表,您必须通过以下索引访问它:
ShowWeather.Text = data.weather[0].description;