2016-07-29 79 views
0

我正在做一些簡單的項目來學習新事物。我開始用SwiftyJSON解析JSON。我試圖向tableView顯示一些JSON數據,但現在我卡住了。我不知道哪裏是零,爲什麼。你能幫助我嗎?在給定的代碼中,我試圖獲取"Brands"並在tableView內顯示它們,或者至少將它們打印到console中。在解析Swift中的JSON時爲零

這是.json文件我有:

{ 
    "Snuses": { 
     "Brands":{ 


      "CATCH": [ 
         {"Products":"white", "nicotine":"8.0"}, 
         {"Products":"yellow", "nicotine":"8.0"} 
         ], 
      "GENERAL": [ 
         {"Products":"brown", "nicotine":"8.0"}, 
         {"Products":"white", "nicotine":"8.0"} 
         ] 
     } 
    } 
} 

在這裏,我試圖得到這樣的信息:

var numberOfRows = 0 

var snusBrandsArray = [String]() 

override func viewDidLoad() { 
    super.viewDidLoad() 
    parseJSON() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

func parseJSON(){ 
    let path: String = NSBundle.mainBundle().pathForResource("snuses", ofType: "json") as String! 
    let jsonData = NSData(contentsOfFile: path) as NSData! 
    let readableJSON = JSON(data: jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) 

    var brands = readableJSON["Snuses", "Brands"] 

    NSLog("\(brands)") 

    numberOfRows = readableJSON["Snuses"].count 

    for i in 1...numberOfRows{ 
     var brands = "Snuses" 
     brands += "\(i)" 
     var name = readableJSON["Snuses", "Brands"].string as String! 
     snusBrandsArray.append(name) 
    } 
} 
+0

大多數指標從0開始。你有沒有試圖改變for循環開始與0?我還沒有嘗試過SwiftyJSON。 – kometen

+0

@kometen是的,我試過了。 –

+0

你究竟想要什麼? 'Brands'有兩個屬性'catch'和'general',它們是''字典''的數組。你是否需要字典值,如「{」產品「:」白色「,」尼古丁「:」8.0「}或品牌名稱爲」catch「和」general「? – triandicAnt

回答

1

怎麼樣簡單的東西,這樣的嗎?下面是Playground代碼,但解析是一樣的。

//: Playground 

import UIKit 
import Foundation 

var jsonStr = "{ \"Snuses\": { \"Brands\":{ \"CATCH\": [ {\"Products\":\"white\", \"nicotine\":\"8.0\"}, {\"Products\":\"yellow\", \"nicotine\":\"8.0\"} ], \"GENERAL\": [ {\"Products\":\"brown\", \"nicotine\":\"8.0\"}, {\"Products\":\"white\", \"nicotine\":\"8.0\"} ] } } }" 

func parseJSON(jsonStr:String) throws -> [AnyObject]? { 

    var brandNameKeys:[AnyObject]? 
    let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 

    let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions()) 

    if let brandNameDict = json["Snuses"]!?["Brands"] as? NSDictionary 
    { 
     brandNameKeys = brandNameDict.allKeys 
    } 

    return brandNameKeys 
} 

if let result = try parseJSON(jsonStr) 
{ 
    print(result) 
} 

在我的遊樂場這個輸出["CATCH", "GENERAL"]我認爲這是你想要的。

這裏是一個完整的UITableViewController演示使用的解決方案:

import UIKit 

class TableViewController: UITableViewController { 

    var data:[AnyObject]? 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     if let path: String = NSBundle.mainBundle().pathForResource("Data", ofType: "json") 
     { 
      do 
      { 
       let jsonStr = try String(contentsOfFile: path) 
       data = try parseJSONStr(jsonStr) 
      } 
      catch _ { 
       print("Loading json failed") 
      } 
     } 
    } 


    // JSON Parsing 
    func parseJSONStr(jsonStr:String) throws -> [AnyObject]? { 

     var brandNameKeys:[AnyObject]? 
     let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 

     let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions()) 

     if let brandNameDict = json["Snuses"]!?["Brands"] as? NSDictionary 
     { 
      brandNameKeys = brandNameDict.allKeys 
     } 

     return brandNameKeys 
    } 

    // MARK: - Table view data source 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if let data = data 
     { 
      return data.count 
     } 
     else 
     { 
      return 0 
     } 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("SampleCell", forIndexPath: indexPath) 

     if let rowData = data![indexPath.row] as? String 
     { 
      cell.textLabel?.text = rowData 
     } 

     return cell 
    } 
} 
+0

您的回答很好,但如果我有大約30個品牌和1000個產品,該怎麼辦?閱讀jsonStr變量將是令人討厭的。 –

+0

如果您的數據量很大,那麼JSON格式不適用於數據(無論您存儲或格式化它)。你應該把它加載到數據庫或CoreData中,並從那裏填充你的tableview。 –

+0

那麼firebase應該做到這一點?那麼這個:https://codeshare.io/Y50HC是太多的數據了? –