如何从Swift 3.0中返回的json中获取特定值?

时间:2016-11-06 05:59:45

标签: json swift swift3

我试图从Swift的json中获取一个值。我添加了数据树的图像。我之前的尝试没有奏效。下面是打印完整json对象的代码,这是我不想要的。

json树形象 enter image description here

import PlaygroundSupport
import UIKit

let url = URL(string: "https://api.data.gov.sg/v1/transport/taxi-availability")
var request = URLRequest(url: url!);
request.addValue("xxxx", forHTTPHeaderField: "api-key")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    //print(json)

    }//end



//["features"]??[0]?


task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true

3 个答案:

答案 0 :(得分:2)

你只需要对已经出售的json做点什么:

let task = URLSession ... { data, response, error in
    let json = JSONSerialization.jsonObject(...)

    if let json = json as? [String: Any] {
       // now you have a top-level json dictionary
       for key, value in json {
           print("json[\"\(key\")] = \(value)")
       }
    }
}

答案 1 :(得分:1)

我没有验证以下代码,但它应该适用于您提供的子树。 (免责声明:可能有一些错误,但大多数错误)

if let json =  (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:Any]
  , let features = json["features"] as? [Any]
  , let firstFeature = features[0] as? [String:Any]
  , let properties = firstFeature["properties"] as? [String:Any]            
  , let taxiCount = properties["taxi_count"] as? Int 
{
    print(taxiCount)
}

答案 2 :(得分:0)

如果Json是字典

let json = try! JSONSerialization.jsonObject(with: data, options: [])
let jsonDict = json as? NSDictionary
//if you have a key name
let name = jsonDict["name"] as? String
//and so on
//if you have a array in your dictionary
let likes = jsonDict["likes"] as? NSArray
let numberOfLikes = likes.count
for eachLike in likes {
let likerName = eachLike["liker_name"] as? String
}