【问题标题】:Looping through Multidimention/Nested JSON data in Swift 5.1在 Swift 5.1 中循环遍历多维/嵌套 JSON 数据
【发布时间】:2019-11-14 10:23:14
【问题描述】:

我正在尝试弄清楚如何快速处理复杂的多级 JSON 数据。我能够在第一级获取数据。但是我无法通过 JSON 中的嵌套数组检索/循环。到目前为止,我有这个。

       let requestParams = ["appVersion" : "1.0.1" , "installId" : installId , "appToken" :  firebaseToken,
                         "phoneDimensions" : dimentions, "phoneOS" : "1", "os_version" :  systemVersion ]

        AF.request(startAppUrl, method: .post, parameters: requestParams , encoding: JSONEncoding.default).responseString{
            response in
            switch response.result {
                case .success(let data):
                    let dataStr = data.data(using: .utf8)!

                    do{
                        let json = try? JSONSerialization.jsonObject(with: dataStr , options: .allowFragments) as! [String: Any]
                        let rows =  json!["ottHomeRows"] as!  [[String:Any]] //Nested Array

                        for item in rows{
                            print(item)
                        }

                    }
                    catch let error as NSError{
                        print("There is an error \(error)")

                    }

                case .failure(let error):
                    print((error.localizedDescription))
            }
        }

我已经尝试了几种变体,但我总是在将嵌套数组从 Any 类型转换为数组时遇到问题。在上面的代码中,我得到错误无法将 __NSCString 类型的值转换为 NSArray。 我的 json 数据样本在这里https://startv.co.tz/startvott/engine/jsonsample/

【问题讨论】:

    标签: json swift xcode multidimensional-array alamofire


    【解决方案1】:

    我建议对 JSON 使用 Swift 解码器:

    struct SomeResult: Decodable {
        let usDeviceData: SomeResultUsDeviceData
    }
    
    struct SomeResultUsDeviceData: Decodable {
    
        let installId: String
    
        let appLang: SomeResultUsDeviceDataAppLang
    
        /// Encoder keys enum
        private enum CodingKeys: String, CodingKey {
            case installId = "install_id"
            case appLang = "appLang"
        }
    }
    
    struct SomeResultUsDeviceDataAppLang: Decodable {
        // and so on
    }
    

    要获得结果,请使用:

    let parsedResult = try? JSONDecoder().decode(SomeResult.self, from: data)
    

    【讨论】:

    • 我现在有了这个 let dataStr = data.data(using: .utf8)!让 parsedResult = 试试? JSONDecoder().decode(appData.self, from: dataStr) let rows = parsedResult?.usDeviceData for item in rows{ print(item) }
    • 我收到错误类型“ViewController.appDatausDeviceData?”不符合协议'Sequence'
    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多