c# jobject get value code example

Example 1: how to get value from object in c#

var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);

Example 2: jobject c# get value by key

/*
{
    "status": "success",
    "data": {
        "city": "Don Mueang",
        "state": "Bangkok",
        "country": "Thailand",
        "location": {
            "type": "Point",
            "coordinates": [
                100.58994,
                13.91392
            ]
        },
        "current": {
            "weather": {
                "ts": "2021-01-18T04:00:00.000Z",
                "tp": 25,
                "pr": 1018,
                "hu": 53,
                "ws": 3.6,
                "wd": 60,
                "ic": "01d"
            },
            "pollution": {
                "ts": "2021-01-18T04:00:00.000Z",
                "aqius": 107,
                "mainus": "p2",
                "aqicn": 64,
                "maincn": "p1"
            }
        }
    }
}
*/

//using Newtonsoft.Json.Linq;
JObject json = JObject.Parse(jsonString);
var jsonData = json["data"];
var jsonCurrent = jsonData["current"];
var jsonPollution = jsonCurrent["pollution"];
var json_aqius = jsonPollution["aqius"];
var json_aqicn = jsonPollution["aqicn"];
System.Diagnostics.Debug.WriteLine("json_aqius : " + json_aqius.toString());

//ref https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm