Home > Software design >  How to get specific JSON property from API using NewtonSoft JObject
How to get specific JSON property from API using NewtonSoft JObject

Time:09-18

I am calling an API and passing the result into a class I have to store the data. However, I am struggling to get a specific property from it. Whenever I try, it returns a null value. I am not good with JSON and other related questions haven't helped, am I just an idiot? Here is the JSON response, how can I get the temp property?

[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

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

CodePudding user response:

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

CodePudding user response:

first, you need to make sure your JSON object has the correct format, in your case, there are 2 possibilities:
1- a root object with one property:

{
   "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:

// 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

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

in this case, you will Deserialize the string as JArray and process your data

// 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>());
}

  • Related