2016-07-29 3 views
0

새로운 것들을 배우기위한 몇 가지 간단한 프로젝트를 수행하고 있습니다. 으로 JSON을 구문 분석하기 시작했습니다. tableView에 일부 JSON 데이터를 표시하려하지만 지금은 붙어 있습니다. 나는 어디에서 왜 없는지, 왜 그런지 모릅니다. 너희들 나를 도울 수 있니? 주어진 코드에서 "Brands"을 얻고 tableView 안에 표시하거나 적어도 console에 인쇄하려고합니다.Swift에서 JSON을 구문 분석하는 동안 nil

이것은 내가 가지고있는 .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

대부분의 인덱스는 for 루프는 0으로 시작하는 변경을 시도 해 봤나 0에서 시작 :

여기에 사용되는 솔루션을 시연 전체있는 UITableViewController이야? 나는 SwiftyJSON을 시도하지 않았다. – kometen

+0

@kometen 그래, 나는 그것을 시도했다. –

+0

정확히 무엇을 원하니? '브랜드'는 '잡다'와'일반'이라는 두 가지 속성을 가지고 있는데'사전'의 배열이다. '{ "Products": "white", "nicotine": "8.0"}'또는 브랜드 이름을'catch '및'general'와 같은 사전 값으로 원하십니까? – triandicAnt

답변

1

무엇을이 같은 간단한 일, 어떻습니까? 아래는 운동장 코드이지만 구문 분석은 같습니다.

//: 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"]을 출력합니다.

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로로드하고 거기에서 테이블 뷰를 채워야합니다. –

+0

그래서 소방차가해야합니까? 그렇다면 : https://codeshare.io/Y50HC가 너무 많은 데이터입니까? –

관련 문제