簡體   English   中英

在Swift 2中將JSON轉換為數組

[英]Converting JSON to array in Swift 2

我需要為Grouped UITableView構建Arrays ,每個表格單元格中都有一個Title和Detail行。 我從服務器獲得了json輸出,使其形狀正確,以迭代UITableViewDataSource方法。 但是將這些轉換為UITableView函數可以引用的可UITableView組的最簡單方法是什么?

標題數組用於組標題,因此它只是一維數組。 我可以迭代一下。 標題和細節數組都是二維的。 我無法弄清楚如何在Swift中做到這一點。

"headings":["Tuesday, August 16, 2016","Wednesday, August 17, 2016","Thursday, August 18, 2016","Friday, August 19, 2016","Saturday, August 20, 2016","Sunday, August 21, 2016","Monday, August 22, 2016","Tuesday, August 23, 2016","Wednesday, August 24, 2016","Thursday, August 25, 2016","Friday, August 26, 2016","Saturday, August 27, 2016","Sunday, August 28, 2016","Monday, August 29, 2016","Tuesday, August 30, 2016","Wednesday, August 31, 2016","Thursday, September 1, 2016","Friday, September 2, 2016","Saturday, September 3, 2016","Sunday, September 4, 2016","Monday, September 5, 2016","Tuesday, September 6, 2016","Wednesday, September 7, 2016","Thursday, September 8, 2016","Friday, September 9, 2016","Saturday, September 10, 2016","Sunday, September 11, 2016","Monday, September 12, 2016","Tuesday, September 13, 2016","Wednesday, September 14, 2016","Thursday, September 15, 2016","Friday, September 16, 2016"],

"titles":[["Joe Johnson"],["Joe Johnson"],["Sandy Primmell","Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Sandy Primmell","Joe Johnson"],["Joe Johnson","Joe Johnson"],["Sandy Primmell","Joe Johnson"],["Mark Greene","Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Sandy Primmell","Joe Johnson"],["Joe Johnson"],["Sandy Primmell","Joe Johnson"],["Mark Greene","Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"],["Joe Johnson"]],

"details":[["OFF"],["OFF"],["Gregory","OFF"],["Gregory"],["OFF"],["OFF"],["OFF"],["Weekday Rounders","OFF"],["Weekday Rounders","Night Owls"],["Gregory","OFF"],["Gregory","OFF"],["OFF"],["OFF"],["OFF"],["Gregory"],["Gregory","OFF"],["Gregory"],["Gregory","OFF"],["Gregory","OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"],["OFF"]]

UPDATE

這是抓取數據的Alamofire異步函數:

manager.request(.POST, getRouter(), parameters:["dev": 1, "app_action": "schedule", "type":getScheduleType(), "days_off":getScheduleDaysOff(), "period":getSchedulePeriod(), "begin_date":getScheduleBeginDate(), "end_date":getScheduleEndDate()])
        .responseString {response in
            print(response)
            var json = JSON(response.result.value!);
// what I'm missing
   }

你可以使用這個功能:

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncodi‌​ng(NSUTF8StringEncodi‌​ng) {
        do {
            return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

然后你可以像這樣讀取數組:

if let dict = convertStringToDictionary(jsonText) {
    let array = dict["headings"] as? [String]
}

看起來你從json獲取Dictionary並且每個鍵都包含Array ,你可以嘗試這樣的東西,首先聲明一個Dictionary實例並將其與TableViewDataSource方法一起使用。

var response = [String: AnyObject]()

do {
     self.response = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! [String: AnyObject]
     print(dic)
}
catch let e as NSError {
     print(e.localizedDescription)
}

現在在tableView方法中

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let arr = self.response["headings"] as? [String] {
        return arr.count
    }
    return 0
}

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let headings = self.response["headings"] as! [String]
    return headings[Int]
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let arr = self.response["titles"] as? [[String]] {
        return arr[Int].count
    }
    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let titles = self.response["titles"] as! [[String]]
    let details = self.response["details"] as! [[String]]       
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! EmployeeCell
    cell.mainLabel?.text = titles[indexPath.section][indexPath.row]
    cell.detailLabel?.text = details[indexPath.section][indexPath.row]
    return cell
}

或者,您可以使用JSON解析庫,如ArgoSwiftyJSON ,它們是為簡化JSON解析而創建的。 它們都經過了良好的測試,可以為您處理邊緣情況,例如JSON響應中缺少參數等。

使用Argo的一個例子:

假設JSON響應具有此格式(來自Twitter API

{
  "users": [
    {
      "id": 2960784075,
      "id_str": "2960784075",
      ...
    }
}

1-創建一個Swift類來表示響應

請注意, Response是一個包含User數組的類,這是另一個未在此處顯示的類,但您明白了。

struct Response: Decodable {
    let users: [User]
    let next_cursor_str: String

    static func decode(j: JSON) -> Decoded<Response> {
        return curry(Response.init)
            <^> j <|| "users"
            <*> j <| "next_cursor_str"
    }
}

2-解析JSON

//Convert json String to foundation object
let json: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: [])

//Check for nil    
if let j: AnyObject = json {
  //Map the foundation object to Response object
  let response: Response? = decode(j)
}

使用Swifty的示例

官方文檔中所述

1-將JSON字符串轉換為SwiftyJSON對象

if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    let json = JSON(data: dataFromString)
}

2-訪問特定元素

如果數據是數組,則使用索引

//Getting a double from a JSON Array
let name = json[0].double

如果數據是字典,則使用密鑰

//Getting a string from a JSON Dictionary
let name = json["name"].stringValue

2'-循環元素

排列

//If json is .Array
//The `index` is 0..<json.count's string value
for (index,subJson):(String, JSON) in json {
    //Do something you want
}

字典

//If json is .Dictionary
for (key,subJson):(String, JSON) in json {
   //Do something you want
}

我建議使用AlamofireObjectMapper。 該庫允許您輕松地從json映射對象,如果與Alamofire結合使用,可以在服務器響應上轉換和返回您的對象。 在您的情況下,對象映射本身應如下所示

class CustomResponseClass: Mappable {
    var headings: [String]?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        headings <- map["headings"]
   }
}

這樣就可以解析映射和解析json與tableViewController的邏輯。

AlamofireObjectMapper

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM