C#C
C#3y ago
Eple

❔ JObject find value

I have the following JSON
{
    "sale": {
        "id": "x",
        "transaction": {
            "id": "y",
            "state": "Completed"
        }
    }
}

I want to check if sale.transaction.state == "Completed"
But since the keys sale, transaction and state are optional and not always in the response, I must check for their presence.
Is there a better way than what I have below?
var responseObject = JObject.Parse(responseString);
if (responseObject["sale"] != null && responseObject["sale"]["transaction"] != null && responseObject["sale"]["transaction"]["state"] != null)
{
    if (responseObject.Value<string>("sale.transaction.state") == "Completed")
    {
        Console.WriteLine("Yes");
    }
}
Was this page helpful?