簡體   English   中英

如何檢查 JSON 可以轉換為 Swift 中的字典?

[英]How to check JSON can be converted to dictionary in Swift?

在此處輸入圖像描述

試過這個,但得到錯誤:

var d = (try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as [String: String]
guard let d2 = d else {
    return
}

你可以試試

guard let dic = try? JSONSerialization.jsonObject(with: data) as? [String: String]  else { return }

這里正確的工具是 JSONDecoder,而不是 JSONSerialization:

let d = try JSONDecoder().decode([String: String].self, data)

.mutableContainers在轉換為 Swift 字典時沒有意義。 這會導致它創建NSMutableDictionary對象,這些對象將被轉換為[String: String]與沒有.mutableContainers (但可能需要額外的復制步驟)。

暫無
暫無

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

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