简体   繁体   English

如何使用 NewtonSoft JObject 从 API 获取特定的 JSON 属性

[英]How to get specific JSON property from API using NewtonSoft JObject

I am calling an API and passing the result into a class I have to store the data.我正在调用 API 并将结果传递给 class 我必须存储数据。 However, I am struggling to get a specific property from it.但是,我正在努力从中获得特定的属性。 Whenever I try, it returns a null value.每当我尝试时,它都会返回 null 值。 I am not good with JSON and other related questions haven't helped, am I just an idiot?我不擅长 JSON 和其他相关问题没有帮助,我只是个白痴吗? Here is the JSON response, how can I get the temp property?这是 JSON 响应,如何获取temp属性?

[data, [
  {
    "wind_cdir": "NE",
    "rh": 45,
    "pod": "d",
    "timestamp_utc": "2022-09-17T15:00:00",
    "pres": 1016.5,
    "solar_rad": 697.939,
    "ozone": 292,
    "weather": {
      "icon": "c01d",
      "code": 800,
      "description": "Clear Sky"
    },
    "wind_gust_spd": 3.87,
    "timestamp_local": "2022-09-17T11:00:00",
    "snow_depth": 0,
    "clouds": 0,
    "ts": 1663426800,
    "wind_spd": 3.02,
    "pop": 0,
    "wind_cdir_full": "northeast",
    "slp": 1023.5,
    "dni": 868.86,
    "dewpt": 10.5,
    "snow": 0,
    "uv": 5.5,
    "wind_dir": 38,
    "clouds_hi": 0,
    "precip": 0,
    "vis": 42.88,
    "dhi": 110.13,
    "app_temp": 22.6,
    "datetime": "2022-09-17:15",
    "temp": 23.1,
    "ghi": 719.68,
    "clouds_mid": 0,
    "clouds_low": 0
  }]
]

The error is on line 16错误在第 16 行

using Newtonsoft.Json.Linq;

namespace WeatherGetter
{
    internal class WeatherReport
    {
        public int Temp { get; private set; }
        //public string Condition { get; private set; }
        public WeatherReport(string args)
        {
            JObject weatherData = JObject.Parse(args);
            foreach (var weather in weatherData)
            {
                Console.WriteLine(weather.ToString());
            }
            Temp = weatherData.SelectToken("$.temp").Value<int>(); //ERROR HERE
            Console.WriteLine($"Temperature: {Temp}");
        }
    }
}

you can use this code你可以使用这个代码

 JArray data = (JArray) JObject.Parse(args)["data"];

  double temp= (double) data[0]["temp"];

  //or

  foreach (var prop in data[0])
        Console.WriteLine(prop.ToString());

first, you need to make sure your JSON object has the correct format, in your case, there are 2 possibilities:首先,您需要确保您的 JSON object 格式正确,在您的情况下,有两种可能性:
1- a root object with one property: 1- 具有一个属性的根 object:

{
   "data": [
      {
          "wind_cdir": "NE",
          "rh": 45,
          "pod": "d",
           ...
          "temp": 23.1,
           ...
      }
   ]
}

if it is this case, then to access your data you need first to access the root "data" property and then read it as a JArray:如果是这种情况,那么要访问您的数据,您首先需要访问根“数据”属性,然后将其作为 JArray 读取:

// Deserialize the JSON string as a JObject
var jsonObject = JsonConvert.DeserializeObject<JObject>(jsonString);

// Read the data property as a JArray
var data = jsonObject["data"] as JArray;

// loop each item in the jArray
foreach (JToken item in data)
{
   Console.WriteLine(item["temp"].Value<int>());
}

2- a collection of objects 2-对象的集合

[
   {
      "wind_cdir": "NE",
      "rh": 45,
      "pod": "d",
      ...
      "temp": 23.1,
      ...
   }
]

in this case, you will Deserialize the string as JArray and process your data在这种情况下,您会将字符串反序列化为 JArray 并处理您的数据

// Deserialize the JSON string as a JArray
var data = JsonConvert.DeserializeObject<JArray>(jsonString);

// loop each item in the jArray
foreach (JToken item in data)
{
   Console.WriteLine(item["temp"].Value<int>());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM