'JsonElement and null conditional operator (KeyNotFoundException)
I have a JSON object that I get from API and I need to check for error in the response of the JSON. However, when there is no error the error value is not present. Also note that API is not reliable and I cannot create POCO out of it, it's out of the question.
Because of that I get KeyNotFoundException
, is there any way to use some kind of conditional operator a.k.a. "Elvis" operator when working with deep nested JsonElements?
I've tried to do ?.GetProperty
but it says Operator '?' cannot be applied to operand of type 'JsonElement'
.
So what are my options here, do I really have to TryGetProperty
and create 3 variables in this example? And if my JSON is more deeply nested I have to create variable for every nest and then check if it is null? Seems kind of ridiculous, there has to be another way.
Here is also an old issue regarding this topic on GitHub. (https://github.com/dotnet/runtime/issues/30450) I thought maybe someone knows some workaround to this problem.
For example, here is my code:
var isError = !string.IsNullOrEmpty(json.RootElement.GetProperty("res")
.GetProperty("error")
.GetProperty("message")
.GetString()); // Throws KeyNotFoundException when `error` or `message` or `res` is not there
Solution 1:[1]
You can write an extension method which return Nullable<JsonElement>
if property not found. like as follows
public static class JsonElementExtenstion
{
public static JsonElement? GetPropertyExtension(this JsonElement jsonElement, string propertyName)
{
if (jsonElement.TryGetProperty(propertyName, out JsonElement returnElement))
{
return returnElement;
}
return null;
}
}
Now the operator ?.
can be applied in your code :
var isError = !string.IsNullOrEmpty(json.RootElement.GetPropertyExtension("res")
?.GetPropertyExtension("error")
?.GetPropertyExtension("message")
?.GetString());
Check this dotnet fiddle which replicates the usage of extension method - https://dotnetfiddle.net/S6ntrt
Solution 2:[2]
This is more correct.
public static JsonElement? GetPropertyExtension(this JsonElement jsonElement, string propertyName)
{
if (jsonElement.ValueKind == JsonValueKind.Null)
{
return null;
}
if (jsonElement.TryGetProperty(propertyName, out JsonElement returnElement))
{
return returnElement;
}
return null;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user1672994 |
Solution 2 | Mats Westerberg |