簡體   English   中英

JsonElement 和 null 條件運算符 (KeyNotFoundException)

[英]JsonElement and null conditional operator (KeyNotFoundException)

我有一個從 API 獲得的 JSON object ,我需要檢查 Z0ECD11Z8D7A2D7401DBB 的響應中是否有錯誤。 但是,當沒有錯誤時,錯誤值不存在。 另請注意,API 不可靠,我無法從中創建 POCO,這是不可能的。

因為我得到KeyNotFoundException ,有沒有辦法在使用深度嵌套的 JsonElements 時使用某種條件運算符,也就是“Elvis”運算符?

我試過做?.GetProperty但它說Operator '?' cannot be applied to operand of type 'JsonElement' Operator '?' cannot be applied to operand of type 'JsonElement'

那么我在這里有什么選擇,在這個例子中我真的需要TryGetProperty並創建 3 個變量嗎? 如果我的 JSON 嵌套更深,我必須為每個嵌套創建變量,然后檢查它是否是 null? 似乎有點荒謬,必須有另一種方式。

這里還有一個關於 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

如果找不到屬性,您可以編寫一個返回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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM