【问题标题】:How to check JSON can be converted to dictionary in Swift?如何检查 JSON 是否可以在 Swift 中转换为字典?
【发布时间】:2020-03-17 09:48:19
【问题描述】:

试过了,但报错:

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

【问题讨论】:

  • as? 带有问号。但是[String: Any] 可能会更好。请注意,JSONSerialization.ReadingOptions.mutableContainers 对 Swift 字典毫无用处。

标签: swift guard


【解决方案1】:

这里正确的工具是 JSONDecoder,而不是 JSONSerialization:

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

.mutableContainers 在转换为 Swift 字典时没有意义。这会导致它创建NSMutableDictionary 对象,这些对象将被转换为[String: String],与没有.mutableContainers 完全相同(但可能需要额外的复制步骤)。

【讨论】:

    【解决方案2】:

    你可以试试

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

    【讨论】:

    • 嗨!为什么在try? 中需要?
    猜你喜欢
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 2018-03-30
    • 2010-12-28
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多