❔ JObject find value
I have the following JSON
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?
5 Replies
You can use
?
with []
: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-
So, if (responseObject["sale"]?["transaction"]?["state"] ...)
or so?Member access and null-conditional operators and expressions:
C# operators that you use to access type members or null-conditionally access type members. These operators include the dot operator -
.
, indexers - [
, ]
, ^
and ..
, and invocation - (
, )
.Like this ig?
easier to debug
Why not just
responseObject["sale"]?["transaction"]?["state"]?.Value<string>() == "Completed"
?These are the kind of answers that I come to this channel for. Smart and brilliant ones.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.