从天气API解析JSON

时间:2019-05-03 16:06:26

标签: c# json parsing

我正在尝试从https://www.worldweatheronline.com的api解析响应。

我得到了这些结果(由于帖子中的字符限制,我将其简化了):

{{
  "data": {
    "request": [
      {
        "type": "LatLon",
        "query": "Lat 33.41 and Lon -86.94"
      }
    ],
    "nearest_area": [
      {
        "areaName": [
          {
            "value": "Brickyard Junction"
          }
        ],
        "country": [
          {
            "value": "United States of America"
          }
        ],
        "region": [
          {
            "value": "Alabama"
          }
        ],
        "latitude": "33.410",
        "longitude": "-86.942",
        "population": "0",
        "weatherUrl": [
          {
            "value": "http://api-cdn.worldweatheronline.com/v2/weather.aspx?q=33.408696,-86.937835"
          }
        ]
      }
    ],
    "weather": [
      {
        "date": "2019-03-20",
        "astronomy": [
          {
            "sunrise": "06:52 AM",
            "sunset": "06:59 PM",
            "moonrise": "06:47 PM",
            "moonset": "06:51 AM",
            "moon_phase": "Waxing Gibbous",
            "moon_illumination": "97"
          }
        ],
        "maxtempC": "20",
        "maxtempF": "69",
        "mintempC": "8",
        "mintempF": "46",
        "totalSnow_cm": "0.0",
        "sunHour": "11.6",
        "uvIndex": "5",
        "hourly": [
          {
            "time": "0",
            "tempC": "9",
            "tempF": "49",
            "windspeedMiles": "4",
            "windspeedKmph": "7",
            "winddirDegree": "65",
            "winddir16Point": "ENE",
            "weatherCode": "113",
            "weatherIconUrl": [
              {
                "value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png"
              }
            ],
            "weatherDesc": [
              {
                "value": "Clear"
              }
            ],
            "precipMM": "0.0",
            "humidity": "53",
            "visibility": "10",
            "pressure": "1026",
            "cloudcover": "2",
            "HeatIndexC": "9",
            "HeatIndexF": "49",
            "DewPointC": "0",
            "DewPointF": "33",
            "WindChillC": "9",
            "WindChillF": "47",
            "WindGustMiles": "7",
            "WindGustKmph": "11",
            "FeelsLikeC": "9",
            "FeelsLikeF": "47",
            "uvIndex": "0"
          },
          {
            "time": "100",
            "tempC": "9",
            "tempF": "49",
            "windspeedMiles": "4",
            "windspeedKmph": "6",
            "winddirDegree": "70",
            "winddir16Point": "ENE",
            "weatherCode": "113",
            "weatherIconUrl": [
              {
                "value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png"
              }
            ],
            "weatherDesc": [
              {
                "value": "Clear"
              }
            ],
            "precipMM": "0.0",
            "humidity": "54",
            "visibility": "10",
            "pressure": "1026",
            "cloudcover": "2",
            "HeatIndexC": "9",
            "HeatIndexF": "49",
            "DewPointC": "0",
            "DewPointF": "33",
            "WindChillC": "9",
            "WindChillF": "47",
            "WindGustMiles": "6",
            "WindGustKmph": "10",
            "FeelsLikeC": "9",
            "FeelsLikeF": "47",
            "uvIndex": "0"
          },
          {
            "time": "200",
            "tempC": "9",
            "tempF": "48",
            "windspeedMiles": "4",
            "windspeedKmph": "6",
            "winddirDegree": "76",
            "winddir16Point": "ENE",
            "weatherCode": "116",
            "weatherIconUrl": [
              {
                "value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
              }
            ],
            "weatherDesc": [
              {
                "value": "Partly cloudy"
              }
            ],
            "precipMM": "0.0",
            "humidity": "55",
            "visibility": "10",
            "pressure": "1026",
            "cloudcover": "1",
            "HeatIndexC": "9",
            "HeatIndexF": "48",
            "DewPointC": "0",
            "DewPointF": "33",
            "WindChillC": "8",
            "WindChillF": "47",
            "WindGustMiles": "5",
            "WindGustKmph": "9",
            "FeelsLikeC": "8",
            "FeelsLikeF": "47",
            "uvIndex": "0"
          },
          {
            "time": "300",
            "tempC": "9",
            "tempF": "48",
            "windspeedMiles": "3",
            "windspeedKmph": "5",
            "winddirDegree": "82",
            "winddir16Point": "E",
            "weatherCode": "116",
            "weatherIconUrl": [
              {
                "value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png"
              }
            ],
            "weatherDesc": [
              {
                "value": "Partly cloudy"
              }
            ],
            "precipMM": "0.0",
            "humidity": "56",
            "visibility": "10",
            "pressure": "1025",
            "cloudcover": "1",
            "HeatIndexC": "9",
            "HeatIndexF": "48",
            "DewPointC": "0",
            "DewPointF": "33",
            "WindChillC": "8",
            "WindChillF": "47",
            "WindGustMiles": "5",
            "WindGustKmph": "8",
            "FeelsLikeC": "8",
            "FeelsLikeF": "47",
            "uvIndex": "0"
          },

我正在尝试将json结果解析回去并获取空值。

private async Task<List<HourData>> GetDataAsync()
{
  try
  {
    var datas = new List<HourData>();
    HttpResponseMessage response = await client.GetAsync(_url);
    if (response.IsSuccessStatusCode)
    {
      var content = await response.Content.ReadAsStringAsync();

      JObject obj = JObject.Parse(content);

      var token = obj.SelectToken("weather"); // *** NullReferenceException HERE
      var tokenHours = (JArray) token.SelectToken("hourly");

      foreach (var tk in tokenHours)
      {
        var json = JsonConvert.SerializeObject(tk);
        datas.Add(JsonConvert.DeserializeObject<HourData>(json));
      }
    }
    // return product;

    return datas;

  }
  catch (Exception e)
  {
    Console.WriteLine(e);
    throw;
  }
}

  public class HourData
  {
    public string Time { get; set; }
    public string Summary { get; set; }
    public string Icon { get; set; }
    public string PrecipIntensity { get; set; }
    public string PrecipProbability { get; set; }
    public string Temperature { get; set; }
    public string ApparentTemperature { get; set; }
    public string DewPoint { get; set; }
    public string Humidity { get; set; }
    public string Pressure { get; set; }
    public string windSpeed { get; set; }
    public string windGust { get; set; }
    public string windBearing { get; set; }
    public string cloudCover { get; set; }
    public string uvIndex { get; set; }
    public string visibility { get; set; }
  }

此行NullReferenceException上有一个var token = obj.SelectToken("weather");

我也尝试了以下方法并获得了相同的结果:

      var token = obj.SelectToken("data");
      var tokenHours = (JArray) token.SelectToken("weather");

我需要将每小时数据输入到我的班级数组中,但无法解析。

我在解析错误的单词吗?我不知道为什么它无法正确解析。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您没有找到正确的元素。

更改以下两行:

var token = obj.SelectToken("weather"); // *** NullReferenceException HERE
var tokenHours = (JArray) token.SelectToken("hourly");

收件人:

var token = obj.SelectToken("data.weather"); // *** NO NULL EXCEPTION HERE
var tokenHours = (JArray)token[0].SelectToken("hourly");

修正了您的代码。

首先,天气在数据元素内。 其次,天气是一个数组,因此您需要处理正确的索引(或者可以将其更改为循环)。