【问题标题】:How do I get a specific value from returned json in Swift 3.0?如何从 Swift 3.0 中返回的 json 中获取特定值?
【发布时间】:2016-11-06 05:59:45
【问题描述】:

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

json 树图像

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

【问题讨论】:

标签: json swift swift3


【解决方案1】:

你只需要对你出售的 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)")
       }
    }
}

【讨论】:

  • 在 Swift 3 中,JSON 字典是 [String:Any]
【解决方案2】:

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

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)
}

【讨论】:

  • 我知道这已经很晚了,但是,当我输入类似“功能”的内容时,它说使用未解析的标识符“功能”,有解决方案吗? @DerrickHo328
【解决方案3】:

如果 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
}

【讨论】:

    猜你喜欢
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2017-09-19
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多