gpt4 book ai didi

json - 在 Swift 中解析 JSON 时为 nil

转载 作者:行者123 更新时间:2023-11-28 16:19:24 24 4
gpt4 key购买 nike

我正在做一些简单的项目来学习新事物。我开始使用 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)
}

在我的 Playground 中,这输出 ["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
}
}

关于json - 在 Swift 中解析 JSON 时为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38663130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com