【问题标题】:JsonElement and null conditional operator (KeyNotFoundException)JsonElement 和空条件运算符 (KeyNotFoundException)
【发布时间】:2020-11-29 08:37:29
【问题描述】:

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

因为我得到了KeyNotFoundException,有没有办法在使用深层嵌套的 JsonElements 时使用某种条件运算符,也就是“猫王”运算符?

我试过?.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

【问题讨论】:

    标签: c# json .net .net-core system.text.json


    【解决方案1】:

    您可以编写一个扩展方法,如果找不到属性,则返回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

    【讨论】:

      猜你喜欢
      • 2017-12-01
      • 2017-08-25
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      相关资源
      最近更新 更多