C
C#2y ago
Eple

❔ JObject find value

I have the following JSON
{
"sale": {
"id": "x",
"transaction": {
"id": "y",
"state": "Completed"
}
}
}
{
"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");
}
}
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");
}
}
5 Replies
canton7
canton72y ago
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 - (, ).
Anton
Anton2y ago
Like this ig?
var sale = responseObject["sale"];
if (sale is null)
return false;

var transaction = sale["transaction"];
if (transaction is null)
return false;

var state = transaction["state"];
if (state is null)
return false;

if (state.Value<string>() == "Completed")
return true;

return false;
var sale = responseObject["sale"];
if (sale is null)
return false;

var transaction = sale["transaction"];
if (transaction is null)
return false;

var state = transaction["state"];
if (state is null)
return false;

if (state.Value<string>() == "Completed")
return true;

return false;
easier to debug
canton7
canton72y ago
Why not just responseObject["sale"]?["transaction"]?["state"]?.Value<string>() == "Completed"?
Eple
EpleOP2y ago
These are the kind of answers that I come to this channel for. Smart and brilliant ones.
Accord
Accord2y ago
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.

Did you find this page helpful?