如何在 swift 中使用 NSDictionary 访问 JSON 子字段

Posted

技术标签:

【中文标题】如何在 swift 中使用 NSDictionary 访问 JSON 子字段【英文标题】:How can access JSON subfield using NSDictionary in swift 【发布时间】:2021-01-04 05:37:31 【问题描述】:

我的第一个 JSON 如下:


    "status": 1

我的代码如下:

let dict: NSDictionary!=(try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
print(dict.value(forKey: "status")!)

使用上述代码使用单个 JSON 字段成功访问。

我的第二个 JSON 如下:


    "status": 
        "subvalue": "true"
    

我尝试使用以下代码。但没有运气。

print(dict?["status "]??["subvalue"])
//or
print(dict.value(forKey: ["status ","subvalue"]))

还有其他方法可以访问这个子 JSON 字段吗?

【问题讨论】:

第二个 JSON 无效。而且这两行代码中有很多不好的做法:NSDictionaryNSData、隐式解包可选类型注释、mutableContainers、(强制解包)valueForKeytry! 感谢您的回复,对不起,我是ios开发的新手。匆忙中,我忘了检查第二个 JSON。我编辑我的问题。 【参考方案1】:

试试这个,它可能对你有用。

if let status = dict["status"] as? [String: Any]

  print(status["subvalue"])


【讨论】:

感谢您的回复。它没有给出正确的值。它给出了一个可选的(1)。我用这条线dict["status"] as? [String:Any] 只需添加 ! 即可删除可选 使用! 会出现如下错误:Initializer for conditional binding must have Optional type, not '[String : Any]' 抱歉使用 dict["status"] as? [String:String] 或 dict["status"] 作为! [字符串:字符串] ?? ["":""] 并像这样打印它print(status["subvalue"]) 如果为假则返回 0,如果为真则返回 1【参考方案2】:

如果您坚持使用 JSONSerialization,这将为您提供 subvalue 的值(如果存在)

if let result = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
   let status = result["status"] as? [String: String],
   let subvalue = status["subvalue"] 
    print(subvalue)

但最好还是长期了解 Codable(在这种情况下为可解码),因为您的代码会更干净且问题更少,尽管开销很小。

struct Root: Decodable 
    let status: Status

struct Status: Decodable 
    let subvalue: String


do 
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result.status.subvalue)

【讨论】:

@NikunjChaklasiya 对此有何反馈?【参考方案3】:

我已经更改了我的答案以获得更好的方法,如果您真的不想解码为模型类,那么您仍然可以采用这种方法。

if let status = a["status"] as? NSDictionary 
    if let subvalue = status["subvalue"] as? String 
        print(subvalue) // your fully wrapped value
    

【讨论】:

不要使用 NSDictionary 也不要强制展开

以上是关于如何在 swift 中使用 NSDictionary 访问 JSON 子字段的主要内容,如果未能解决你的问题,请参考以下文章