无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型,因为该类型需要 JSON 对象(例如 { "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, "主要":"雨", "描述":"小雨", "图标":" 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;

相关内容

  • 没有找到相关文章

最新更新