在Swift 5.1中循环遍历多维/嵌套JSON数据

我试图弄清楚如何快速处理复杂的多层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类型转换为array的问题。在上面的代码中,我得到了错误,无法将__NSCString类型的值转换为NSArray。 我的json数据示例位于https://startv.co.tz/startvott/engine/jsonsample/

jessiebonbon 回答:在Swift 5.1中循环遍历多维/嵌套JSON数据

我建议将Swift Decoder用于JSON:

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)
本文链接:https://www.f2er.com/3103500.html

大家都在问