Search code examples
c#json.netjson.net

How to check if a nested list of objects inside a JSON response is empty or not?


I've a JSON which I'm getting from

var responseMessage1 = await request1.Content.ReadAsStringAsync();

which looks like this : -

{
    "operations": [
        {
            "creationTime": "2022-06-02T10:28:28.765+03:00",
            "deviceId": "43432103",
            "deviceName": "P25-SC-0228",
            "status": "PENDING",
            "com_cumulocity_model": {
                "op": "s",
                "param": "waterStartDateTime",
                "value": "1/2/2018, 7:30:00 AM"
            },
            "description": "Generate Plan"
        },
        {
            "creationTime": "2022-06-02T10:28:36.276+03:00",
            "deviceId": "43432103",
            "deviceName": "P25-SC-0228",
            "status": "PENDING",
            "com_cumulocity_model": {
                "Mode": 0,
                "StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
            },
            "description": "Stop Station"
        }
    ],
    "statistics": {
        "currentPage": 1,
        "pageSize": 5
    }
}

What I want to achieve is to check for a condition if the operations list inside the json is empty or not, where the json might look like this: -

{
    "operations": [],
    "statistics": {
        "currentPage": 1,
        "pageSize": 1
    }
}

I want to perform something like

if(responseMessage1["operations"] != null){
//do something
}

Solution

  • You can use the HasValues property of the JToken to do your branching

    if (json["operations"].HasValues)