2016-10-26 75 views
-1

我使用twitter趋势API获取所有趋势的名称。快速解析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数据,我想存储所有的nametrends在快速数组中。

回答

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