【发布时间】: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