【问题标题】:Getting info out of nested json file从嵌套的 json 文件中获取信息
【发布时间】:2019-07-31 18:55:52
【问题描述】:

从网站metcheck我可以得到一个天气预报的json文件。 http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.380&lon=0.060&Fc=Av

文件回来了,但我无法读取它以获取我需要的信息。我想我不明白metcheckData、forecastLocation和forecast之间的关系:

{
   "metcheckData":{
      "forecastLocation":{
         "forecast":[
            {
               "temperature":"18",
               "dewpoint":"13",
               "rain":"0.0",
               "freezinglevel":"3049",
               "uvIndex":"1",
               "totalcloud":"65",
               "lowcloud":"55",
               "medcloud":"43",
               "highcloud":"11",
               "humidity":"79",
               "windspeed":"11",
               "meansealevelpressure":"1012.77",
               "windgustspeed":"17",
               "winddirection":"249",
               "windletter":"WSW",
               "icon":"PC",
               "iconName":"Partly Cloudy",
               "chanceofrain":"0",
               "chanceofsnow":"0",
               "dayOfWeek":"4",
               "weekday":"Wednesday",
               "sunrise":"6:02",
               "sunset":"18:09",
               "cumulusBaseHeight":"540",
               "stratusBaseHeight":"549",
               "dayOrNight":"N",
               "utcTime":"2019-07-31T19:00:00.00"
            },
            {
               "temperature":"17",
               "dewpoint":"13",
               "rain":"0.1",
               "freezinglevel":"3192",
               "uvIndex":"0",
               "totalcloud":"91",
               "lowcloud":"66",
               "medcloud":"39",
               "highcloud":"35",
               "humidity":"82",
               "windspeed":"11",
               "meansealevelpressure":"1013.29",
               "windgustspeed":"17",
               "winddirection":"245",
               "windletter":"WSW",
               "icon":"RO",
               "iconName":"Intermittent Rain",
               "chanceofrain":"47",
               "chanceofsnow":"0",
               "dayOfWeek":"4",
               "weekday":"Wednesday",
               "sunrise":"6:02",
               "sunset":"18:09",
               "cumulusBaseHeight":"512",
               "stratusBaseHeight":"520",
               "dayOrNight":"N",
               "utcTime":"2019-07-31T20:00:00.00"
            }
         ],
         "continent":"",
         "country":"",
         "location":"52.4/0.1",
         "latitude":52.4,
         "longitude":0.1,
         "timezone":0
      }
      // Many other similar array entries omitted
   },
   "feedCreation":"2019-07-31T20:26:10.00",
   "feedCreator":"Metcheck.com",
   "feedModel":"GHX5",
   "feedModelRun":"00Z",
   "feedModelRunInitialTime":"2019-07-31T00:00:00.00",
   "feedResolution":"0.01"
}

使用 使用 Newtonsoft.Json; 使用 Newtonsoft.Json.Linq;

我尝试使用以下代码读取特定时间的温度预测等内容。

 JObject jo = JObject.Parse(File.ReadAllText(@"C:\temp\Weather.json", Encoding.UTF8));
 Dictionary<string, List<string>> values =
            jo.SelectToken("forecast", true).ToObject<Dictionary<string, List<string>>>();

 foreach (var kv in values)
 {
     rchtxtbx_output.AppendText(kv.Value[0] + "\r");

以此类推,认为 kv.Value[0] 将是温度,我将四处走动并获取每小时的温度。不幸的是,事实并非如此,我在

处遇到错误
Dictionary<string, List<string>> values =
                jo.SelectToken("forecast", true).ToObject<Dictionary<string, List<string>>>();

所以有些“预测”是不正确的。我也尝试过metcheckData.forecastLocation.forecast,然后是forecastLocation.forecast,但都有错误。

请告诉我如何从 json 文件中获取数据并为每个小时的预测写入富文本框。

【问题讨论】:

标签: c# json


【解决方案1】:

您想通过其父令牌导航到所需的令牌。然后获取令牌的子列表。

JObject jo = JObject.Parse(File.ReadAllText(@"C:\temp\Weather.json", Encoding.UTF8));

// navigate to the token via its parents
List<JToken> items = jo.SelectToken("metcheckData", true).SelectToken("forecastLocation", true).SelectToken("forecast", true).Children().ToList();

foreach (JToken token in items)    
{
    string temperature = token["temperature"].Value<string>();
    string dewpoint = token["dewpoint"].Value<string>();
    // etc...
}

【讨论】:

    【解决方案2】:

    为什么不创建一个映射类并将 JSON 解析为这个对象。完成后,您可以浏览所有属性并选择所需的所有内容。

    var data = JsonConvert.DeserializeObject<Rootobject>(File.ReadAllText(@"C:\temp\Weather.json", Encoding.UTF8));
    
    public class Rootobject
    {
        public Metcheckdata metcheckData { get; set; }
        public DateTime feedCreation { get; set; }
        public string feedCreator { get; set; }
        public string feedModel { get; set; }
        public string feedModelRun { get; set; }
        public DateTime feedModelRunInitialTime { get; set; }
        public string feedResolution { get; set; }
    }
    
    public class Metcheckdata
    {
        public Forecastlocation forecastLocation { get; set; }
    }
    
    public class Forecastlocation
    {
        public Forecast[] forecast { get; set; }
        public string continent { get; set; }
        public string country { get; set; }
        public string location { get; set; }
        public float latitude { get; set; }
        public float longitude { get; set; }
        public int timezone { get; set; }
    }
    
    public class Forecast
    {
        public string temperature { get; set; }
        public string dewpoint { get; set; }
        public string rain { get; set; }
        public string freezinglevel { get; set; }
        public string uvIndex { get; set; }
        public string totalcloud { get; set; }
        public string lowcloud { get; set; }
        public string medcloud { get; set; }
        public string highcloud { get; set; }
        public string humidity { get; set; }
        public string windspeed { get; set; }
        public string meansealevelpressure { get; set; }
        public string windgustspeed { get; set; }
        public string winddirection { get; set; }
        public string windletter { get; set; }
        public string icon { get; set; }
        public string iconName { get; set; }
        public string chanceofrain { get; set; }
        public string chanceofsnow { get; set; }
        public string dayOfWeek { get; set; }
        public string weekday { get; set; }
        public string sunrise { get; set; }
        public string sunset { get; set; }
        public string cumulusBaseHeight { get; set; }
        public string stratusBaseHeight { get; set; }
        public string dayOrNight { get; set; }
        public DateTime utcTime { get; set; }
    }

    【讨论】:

      【解决方案3】:

      如果您从链接中获取 json 并忽略 forecast 部分,您会得到:

      {
          "metcheckData": {
              "forecastLocation": {
                  "forecast": [],
                  "continent": "",
                  "country": "",
                  "location": "52.4/0.1",
                  "latitude": 52.4,
                  "longitude": 0.1,
                  "timezone": 0
              }
          },
          "feedCreation": "2019-07-31T20:17:52.00",
          "feedCreator": "Metcheck.com",
          "feedModel": "GHX5",
          "feedModelRun": "00Z",
          "feedModelRunInitialTime": "2019-07-31T00:00:00.00",
          "feedResolution": "0.01"
      }
      

      由此,(对我而言)变得更加明显,metacheckDataforecastLocation 都是对象,forecast 数组是 forecastLocation 的属性。

      我会做的是使用dynamics。检查thisthis post

      所以它可能会变成这样(未测试):

      var data = JsonConvert.DeserializeObject<dynamic>(rawJson);
      var rawForecasts = data.metcheckData.forecastLocation.forecast;
      

      【讨论】:

      • 感谢您向我解释这一点,我现在对 JSon 有了更多了解
      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2012-12-23
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多