簡體   English   中英

無法使用swift從json訪問嵌套字典/數組

[英]Can't access nested dictionaries/arrays from json with swift

我試圖訪問本地json文件的[“上類別”] [“第一類”] [0] [0]

{
    "upper category": {
        "first category": [
            [
                "this is a question", 
                "this is an answer", 
                "this is the rank"
            ], 
            [
                "this is a question2", 
                "this is an answer2", 
                "this is the rank2"
            ]
        ], 
        "second category": [
            [
                "this is a question3", 
                "this is an answer3", 
                "this is the rank3"
            ]
        ]
    }
}

let path = Bundle.main.path(forResource: "data", ofType: "json")
do {let data:NSData = try NSData(contentsOfFile: path!)
    let json = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

我無法訪問第一本字典以外的任何內容。

我嘗試了幾次選項(我試過多個較舊的解決方案,但它們似乎對我不起作用,也許很快3)

    if let description = ((((json?["upper category"] as? AnyObject)?["first category"] as? AnyObject)?[0] as? AnyObject)?[0] as? String) {

這可能是一個noob問題,我是ios的新手。 雖然任何答案都非常贊賞,解釋如何為其他數量的嵌套類型編寫代碼是最好的

(xcode 8,swift 3)

這有點矯枉過正,但你可以將json轉換為[String:[String:[[String]]]]

let json = try? JSONSerialization.jsonObject(...) as? [String:[String:[[String]]]]

否則,例如,如果字典包含嵌套字典以外的元素,則只需將頂級字典轉換為[String:Any]並單獨轉換嵌套元素。

if let json = try? JSONSerialization.jsonObject(...) as? [String:Any] {

    let foo = json["foo"] as? Int
    let bar = json["bar"] as? [String:Any]

    ...
}

暫無
暫無

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

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