解析twitter趋势api的结果很快

时间:2016-10-26 17:40:00

标签: json swift3 twitter-fabric

我使用twitter trend 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数据中,我想在swift中将name内的所有trends存储在一个数组中。

1 个答案:

答案 0 :(得分:0)

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

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