簡體   English   中英

在Swift中解析JSON時為nil

[英]nil while parsing JSON in Swift

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

這是我擁有的.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)
    }
}

像這樣簡單的事情呢? 下面是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
    }
}

暫無
暫無

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

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