简体   繁体   English

在Swift中解析JSON时为nil

[英]nil while parsing JSON in Swift

I am doing some easy projects to learn new things. 我正在做一些简单的项目来学习新事物。 I started parsing JSON with SwiftyJSON . 我开始使用SwiftyJSON解析JSON I am trying to show some JSON data to the tableView but now I am stuck. 我正在尝试向tableView显示一些JSON数据,但现在我被卡住了。 I do not know where is the nil and why. 我不知道零在哪里,为什么在哪里。 Can you help me guys? 你能帮我吗? In given code I am trying to get the "Brands" and show them inside tableView or at least print those into console . 在给定的代码中,我试图获取"Brands"并在tableView显示它们,或者至少将它们打印到console

This is the .json file I have: 这是我拥有的.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"}
                        ]
        }
    }
}

And here I try to get the info like this: 在这里,我尝试获取如下信息:

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)
    }
}

What about something simple, like this? 像这样简单的事情呢? Below is Playground code but the parsing is the same. 下面是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)
}

In my Playground this outputs ["CATCH", "GENERAL"] which I think is what you want. 在我的游乐场中,此输出["CATCH", "GENERAL"] ,我认为这是您想要的。

Here's a full UITableViewController demonstrating the solution in use: 这是完整的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