解析推特趋势 api 结果 swift

Parse twitter trend api results in swift

我使用 Twitter 趋势 api 来获取所有趋势的名称。

我有以下设置:

let url =  "\(APIConstants.Twitter.APIBaseURL)1.1/trends/place.json?id=1"

    let client = TWTRAPIClient()
    let statusesShowEndpoint = url
    let params = ["id": "20"]
    var clientError : NSError?

    let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)

    client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: \(connectionError)")
        }

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

        } catch let jsonError as NSError {
            print("json error: \(jsonError.localizedDescription)")
        }


    } 

调用后,json有以下数据:

(
{
    "as_of": "2012-08-24T23:25:43Z",
    "created_at": "2012-08-24T23:24:14Z",
    "locations": [
      {
        "name": "Worldwide",
        "woeid": 1
      }
    ],
    "trends": [
      {
        "tweet_volume": 3200,
        "events": null,
        "name": "#GanaPuntosSi",
        "promoted_content": null,
        "query": "%23GanaPuntosSi",
        "url": "http://twitter.com/search/?q=%23GanaPuntosSi"
      },
      {
        "tweet_volume": 4200,
        "events": null,
        "name": "#WordsThatDescribeMe",
        "promoted_content": null,
        "query": "%23WordsThatDescribeMe",
        "url": "http://twitter.com/search/?q=%23WordsThatDescribeMe"
      },

      {
        "tweet_volume": 2200,
        "events": null,
        "name": "Sweet Dreams",
        "promoted_content": null,
        "query": "%22Sweet%20Dreams%22",
        "url": "http://twitter.com/search/?q=%22Sweet%20Dreams%22"
      }
    ]
  }
)

根据上面的json数据,我想将trends里面的所有name都存储在swift的数组中。

您需要进行一些数据检查和转换,以确保以您期望的结构取回数据,然后从那里进行简单的迭代。沿着这些方向的东西应该让你继续:

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:Any]
var names = [String]()
if let trends = json?["trends"] as? [[String:Any]] {
    for trend in trends {
        if let name = trend["name"] as? String {
            names.append(name)
        }
    }
}

注意各种 as? 类型检查以安全地迭代结构。有关在 Swift 中使用 JSON 进行更深入的回顾,包括将数据读入类型安全的结构,请查看 this official blog post from Apple.