c# - 从 weather api 解析 json

标签 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; }
  }

我在 var token = obj.SelectToken("weather"); 这一行得到了一个 NullReferenceException

我也尝试了以下并得到了相同的结果:

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

我需要将每小时的数据放入我的类数组中,但它没有进行解析。

我是不是分析错了词?我不知道为什么它没有正确解析。

如有任何帮助,我们将不胜感激!

最佳答案

您没有找到正确的元素。

将这 2 行从:

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");

修正了你的代码。

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

关于c# - 从 weather api 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973543/

相关文章:

c++ - boost 变体的 spirit 传承

c# - 如何使用 Azure AD 生成具有角色定义的 token

c# - 如何检查一个数字在文本文件中的特定行中出现了多少次

c# - 在powerpoint中使用OpenXML创建表

ios - 如何在 Swift 中访问 Json Int、Double、String 中的数据?

c# - Web Api 模型绑定(bind)和多态继承

java - 如何使用Nutch抓取并解析精确的数据?

c# - 在 C# 中使用 OLEDB 连接读取 Excel 文件

json - 如何在 iOS9 上做 http 基本认证?

android - xml解析终止