Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 787
Stan Avatar asked Oct 15 '25 17:10

Stan


1 Answers

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

like image 71
user1672994 Avatar answered Oct 18 '25 05:10

user1672994



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!