JsonElement 和 null 条件运算符 (KeyNotFoundException)

JsonElement and null conditional operator (KeyNotFoundException)

我有一个从 API 获得的 JSON 对象,我需要检查 JSON 的响应中的错误。但是,如果没有错误,则错误值不存在。另请注意,API 不可靠,我无法从中创建 POCO,这是不可能的。

因此我得到 KeyNotFoundException,有什么方法可以使用某种条件运算符 a.k.a。使用深层嵌套 JsonElements 时的“Elvis”运算符?

我试过 ?.GetProperty 但它说 Operator '?' cannot be applied to operand of type 'JsonElement'

那么我在这里有什么选择,我真的必须 TryGetProperty 并在此示例中创建 3 个变量吗?如果我的 JSON 嵌套更深,我必须为每个嵌套创建变量,然后检查它是否为空?看起来有点可笑,必须有另一种方式。

GitHub 上还有一个关于此主题的老问题。 (https://github.com/dotnet/runtime/issues/30450) 我想也许有人知道这个问题的解决方法。

例如,这是我的代码:

var isError = !string.IsNullOrEmpty(json.RootElement.GetProperty("res")
    .GetProperty("error")
    .GetProperty("message")
    .GetString()); // Throws KeyNotFoundException when `error` or `message` or `res` is not there

如果 属性 未找到,您可以编写一个扩展方法 return Nullable<JsonElement>。喜欢如下

public static class JsonElementExtenstion
{
    public static JsonElement? GetPropertyExtension(this JsonElement jsonElement, string propertyName)
    {
        if (jsonElement.TryGetProperty(propertyName, out JsonElement returnElement))
        {
            return returnElement;
        }
        
        return null;
    }
}

现在可以在您的代码中应用运算符 ?. :

var isError = !string.IsNullOrEmpty(json.RootElement.GetPropertyExtension("res")
    ?.GetPropertyExtension("error")
    ?.GetPropertyExtension("message")
    ?.GetString());

检查这个重复使用扩展方法的 dotnet fiddle - https://dotnetfiddle.net/S6ntrt

这个比较正确。

 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;
    }