简体   繁体   English

从Swift中URLSession中的json获取值

[英]get the values from json in URLSession in Swift

I am developing an using the JSON .So i am new to this field. 我正在开发使用JSON的工具。因此,我是该领域的新手。 I need to get the values from the url and the pattern is as below mention:- {Data:[{name:RAHUL,place:WORLD,location:[{city:WORLD}]},{},{},{}],mata:{},link:{}} 我需要从url中获取值,并且模式如下所述:-{数据:[{名称:RAHUL,位置:WORLD,位置:[{city:WORLD}]},{},{},{} ],mata:{},link:{}}

I need the "Data" value as the pattern array.That is i need to get the Data values seperate. 我需要“数据”值作为模式数组。也就是说,我需要将数据值分开。 How to get the values name and city values from this 如何从中获取值名称和城市值

Try this way: 尝试这种方式:

let sessionConfig = URLSessionConfiguration.default

        // Create session, and optionally set a URLSessionDelegate
        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

        // Create request
        guard let URL = URL(string: "YOUR_URL_HERE") else { return }
        let request = URLRequest(url: URL)

        let task = session.dataTask(with: request) { (data, response, err) in
            if (err == nil) {
                // Success
                let statusCode = (response as! HTTPURLResponse).statusCode
                print("URL Session Task Succeeded: HTTP \(statusCode)")
                if let data = data {

                    do {
                        let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

                        // Parse JSON data
                        if let json = jsonResult as? [String:Any],
                        let dataArr = json["Data"] as? [[String:Any]] {

                            for item in dataArr {

                                let name = item["name"] as! String
                                // AND SO ON PARSE ANOTHER FIELDS
                            }
                        }

                    } catch let err {
                        print(err)
                    }

                }
            } else {
                // Failure
                print("URL Session Task Failed: \(err!.localizedDescription)")
            }
        }
        task.resume()
        session.finishTasksAndInvalidate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM