[英]Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”})
[英]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '' because the type requires a JSON object (e.g. {“name”:“value”})
我有
“無法將當前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"
}
]
...
}
我得到了錯誤。
JSON包含一個Weather
數組,即使它只有一個條目也是如此。 用方括號表示,請參見下文:
“天氣”: [ {“ id”:500,“ main”:“雨”,“ description”:“小雨”,“ icon”:“ 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.