我正在开发使用JSON。所以我是这个领域的新手。 我需要从网址获取值,模式如下: - {数据:[{名称:RAHUL,地点:WORLD,位置:[{城市:WORLD}]},{},{},{}],马塔:{},链接:{}}
我需要"数据"值作为模式数组。我需要将数据值分开。如何从此
获取值名称和城市值答案 0 :(得分:0)
尝试这种方式:
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()
答案 1 :(得分:-2)
let result = (response as! NSDictionary).object(forKey: "response") as! NSDictionary
let data = result.object(forKey: "Data") as! NSArray
for int i in array.count - 1 {
let dict = data[i] as! NSDictionary
let name = dict.value(forKey: "name") as! String
let location = dict.value(forKey: "location") as! NSArray
let dictLocation = location[0] as! NSDictionary
let city = dictLocation.value(forKey: "city") as! String
}