【问题标题】:accessing nested dictionary json in swift 5在swift 5中访问嵌套字典json
【发布时间】:2021-07-18 20:18:35
【问题描述】:

我希望你在每件事上都做得很好,实际上我想以这些 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!)
                 }
             
            }

【问题讨论】:

  • 请编辑您的帖子以包含代码而不是代码图片,这不利于搜索、屏幕阅读器、复制和粘贴等。

标签: json swift dictionary


【解决方案1】:

我喜欢使用 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)
}

【讨论】:

  • 使用CodableJSONDecoder 绝对是要走的路。 CodingKeys 不是绝对必要的,__v_id 是有效的标识符,如果不是很 Swifty。
  • 非常正确。只需使用来自 QuickType 的直接、未经编辑的输出。
  • 是的,很好的解决方案,谢谢兄弟,终于我得到了我想要的结果,再次感谢,我希望你在回答我的问题后尽快得到答案,我希望这些适合每个程序员。
  • 哇——多么美好的感觉!很高兴我能帮上忙。
  • 非常感谢,你的眼睛看起来很漂亮,干得好
猜你喜欢
  • 2016-07-10
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
  • 2014-10-17
  • 2021-02-08
  • 1970-01-01
相关资源
最近更新 更多