首页 > 解决方案 > 在swift 5中访问嵌套字典json

问题描述

我希望你在每件事上都做得很好,实际上我想以这些 Jason 格式访问 countryId (嵌套字典)中的国家名称,我测试了不同的方式,但不幸的是我不明白解决方案,你能帮我解决吗它?这是我的 json :

[
    {
        "_id": "606836792ed79e4194e98848",
        "title": "berlin",
        "countryId": {
            "_id": "6068366e2ed79e4194e98847",
            "name": "germany",
            "__v": 0
        },
        "__v": 0
    },
    {
        "_id": "60505f8c8acc922dc46a60eb",
        "title": "ezmir",
        "countryId": {
            "_id": "60505f808acc922dc46a60ea",
            "name": "turkey",
            "__v": 0
        },
        "__v": 0
    },
    {
        "_id": "606836942ed79e4194e9884b",
        "title": "karaj",
        "countryId": {
            "_id": "606836832ed79e4194e98849",
            "name": "iran",
            "__v": 0
        },
        "__v": 0
    },
    {
        "_id": "60696c7b1c7a4937a817c463",
        "title": "new york",
        "countryId": {
            "_id": "60696c461c7a4937a817c462",
            "name": "usa",
            "__v": 0
        },
        "__v": 0
    },
    {
        "_id": "60696c0d1c7a4937a817c461",
        "title": "stanbol",
        "countryId": {
            "_id": "60505f808acc922dc46a60ea",
            "name": "turkey",
            "__v": 0
        },
        "__v": 0
    },
    {
        "_id": "6068368d2ed79e4194e9884a",
        "title": "tabriz",
        "countryId": {
            "_id": "606836832ed79e4194e98849",
            "name": "iran",
            "__v": 0
        },
        "__v": 0
    }
]

这也是我想在我的代码中解决它的地方:

  
        func fetchingcityInformation()  {
           let url = "http://192.168.1.199:2581/api/citys"
           
           do {
               let data =  try Data(contentsOf: URL(string: url)!)
               let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            guard let array = json as? [Any] else { return }
            print("the json file is : \(array)")
            print(" country is folan : \(array[2]) ")
            for users in array {
                guard let usersDict = users as? [String: Any] else { return }
             
             guard let names = usersDict["countryId"] as? [String : String] else { return }
                print(" userDict is : \(String(describing: usersDict["countryId"])) ")
             print("the country id is : \(names)")
             // inja boodi
             
             //guard var countryId = user as? [String: Any] else { return }
             
             //countryArray = names
                 if countryPressed == countryArray["name"] {
                     guard (usersDict["title"] as? String) != nil else {
                         return
                     }
                     cityslbl.append(title!)
                 }
             
            }

标签: jsonswiftdictionary

解决方案


我喜欢使用 QuickType.io ( https://app.quicktype.io ) 来处理这类事情。它为 JSON 结构提供了这个:

struct WelcomeElement: Codable {
    let id, title: String
    let countryID: CountryID
    let v: Int

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case title
        case countryID = "countryId"
        case v = "__v"
    }
}

// MARK: - CountryID
struct CountryID: Codable {
    let id, name: String
    let v: Int

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case name
        case v = "__v"
    }
}

然后解码和访问内部元素很容易:

do {
    let root = try JSONDecoder().decode([WelcomeElement].self, from: jsonData)
    root.forEach { (element) in
        print(element.countryID)
        print(element.title)
    }
} catch {
    print(error)
}

可以继续只使用未键入的[String:Any]字典,但它不友好并且很容易出错:

do {
    let json = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)

    guard let array = json as? [[String:Any]] else {
        assertionFailure("Bad cast")
        return
    }
    
    array.forEach { (element) in
        print(element["title"] ?? "unknown")
        if let countryId = element["countryId"] as? [String:String] {
            print(countryId["name"] ?? "unknown")
        }
    }
} catch {
    print(error)
}

推荐阅读