首页 文章

使用Swift访问JSON中的嵌套字典

提问于
浏览
1

我想解析以下JSON,以便从维基百科的API中获取随机文章的ID并在Swift中使用它:

{
"batchcomplete": "",
"continue": {
    "rncontinue": "0.067678657404|0.067678667039|13394072|0",
    "continue": "-||"
},
"query": {
    "random": [
        {
            "id": 34538560,
            "ns": 3,
            "title": "User talk:59.188.42.121"
        }
    ]
}
}

我希望能够从中访问 "id""title" 值,我目前有以下内容来访问 "query"

let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=1&format=json")
    URLSession.shared.dataTask(with: url!) { (data, response, err) in
        guard let data = data else { return }
        if err != nil {
            print(err!)
        } else {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
                if let result = json! as? [String: AnyObject] {
                    if let result = result["query"]! as? [String: AnyObject] {
                        print(result)
                    }
                }
            } catch {
                print("Error")
            }
        }
    }.resume()

现在,输入我的方式并不是我自豪的事情,而且非常快速地让人感到困惑 . 通过做类似下面的事情,我也试过一次类型转换,但没有用:

[String: [String: [String:AnyObject]]]

有没有更好的方法来访问这些值?任何帮助将不胜感激!

1 回答

  • 1

    如果你使用的是Swift 4,那就是 Codable . 使用 Codable 涉及为JSON定义自定义结构/类,但像quicktype.io这样的应用程序可以使这件事情变得轻而易举:您只需粘贴JSON并为您生成结构 .

    首先,保存维基百科响应的结构:

    struct Response: Codable {
        struct Query: Codable {
            let random: [Random]
        }
    
        struct Random: Codable {
            let id, ns: Int
            let title: String
        }
    
        struct Continue: Codable {
            let rncontinue, continueContinue: String
    
            enum CodingKeys: String, CodingKey {
                case rncontinue
                case continueContinue = "continue"
            }
        }
    
        let batchcomplete: String
        let `continue`: Continue
        let query: Query
    
        enum CodingKeys: String, CodingKey {
            case batchcomplete, `continue`, query
        }
    }
    

    并解码JSON:

    let url = URL(string: "https://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=1&format=json")
    URLSession.shared.dataTask(with: url!) { (data, response, err) in
        guard let data = data else { return }
        guard err == nil else { print(err!); return }
    
        do {
            let response = try JSONDecoder().decode(Response.self, from: data)
            if let firstArticle = response.query.random.first {
                print(firstArticle)
            } else {
                print("No Article")
            }
        } catch {
            print(error)
        }
    }.resume()
    

相关问题