解析json数组会在swift中返回空元素

时间:2017-02-11 15:27:03

标签: ios json swift

根据OOPer的建议,我将此作为一个单独的问题发布。这是对此的扩展: JSONserialization error

我从一个读取sql数据库的php脚本中提取一个json数组。 json非常大,但应该使用几个在线测试人员进行测试。问题是,当我尝试从数组中取出元素时,它返回nil。它能够下载数据,并且可以正确计算数组中有多少元素,但是当我尝试访问元素时,它返回nil。有什么建议吗?

以下是元素的示例:

{
"id":2045,
"oprettelsesdato":"09-02",
"overskrift":"etc etc etc",
"navn":"xyz xyz xyz",
"tlf":"12345678",
"email":"etc@etc.etc",
"journal":"MJ",
"intro":"yada yada yada yada ",
"annonce":"test",
"address":"testroad"
},

LocationModel.swift

import Foundation

class LocationModel: NSObject {

//properties

var id: String?
var oprettelsesdato: String?
var overskrift: String?
var address: String?
var intro: String?
var email: String?
var tlf: String?
var annonce: String?
var journalnr: String?


override init()
{

}


init(id: String, oprettelsesdato: String, overskrift: String, address: String, intro: String, email: String, tlf: String, annonce: String, journalnr: String) {

    self.id = id
    self.oprettelsesdato = oprettelsesdato
    self.overskrift = overskrift
    self.address = address
    self.intro = intro
    self.email = email
    self.tlf = tlf
    self.annonce = annonce
    self.journalnr = journalnr

}


override var description: String {
    return "id: \(id), oprettelsesdato: \(oprettelsesdato), overskrift: \(overskrift), address: \(address), journalnr: \(journalnr)"

}



}

以下是抛出错误的地方:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let item: LocationModel = feedItems[indexPath.row] as! LocationModel
    let cellIdentifier: String = "BasicCell"
    let myCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
    print(feedItems[indexPath.row])


    //myCell.detailTextLabel!.text = item.oprettelsesdato
    myCell.textLabel!.text = item.overskrift
    myCell.textLabel!.leadingAnchor.constraint(equalTo: myCell.leadingAnchor).isActive = true
    myCell.textLabel!.topAnchor.constraint(equalTo: myCell.topAnchor).isActive = true
    myCell.textLabel!.heightAnchor.constraint(equalTo: myCell.heightAnchor,
                                                multiplier: 1.0).isActive = true
    myCell.textLabel!.widthAnchor.constraint(equalTo: myCell.heightAnchor,
                                                multiplier: 0.8).isActive = true


    //print(item.id)  <-returns nil
    //print(item.oprettelsesdato)  <-returns nil
    //print(item.overskrift)  <-returns nil
    extralabel!.text = item.oprettelsesdato // <-This is where the error is thrown 

}

错误消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

更新 所以我在json解析器中将其缩小到以下内容。尽管所有jsonElements都包含值,但if let optional永远不会成立。怎么了?

for jsonElement in jsonResult {
        print(jsonElement["id"])  //<- these print() all return the correct values
        print(jsonElement["oprettelsesdato"])
        print(jsonElement["overskrift"])
        print(jsonElement["address"])
        print(jsonElement["intro"])
        print(jsonElement["email"])
        print(jsonElement["tlf"])
        print(jsonElement["annonce"])
        print(jsonElement["journal"])

        let location = LocationModel()
        if let id = jsonElement["id"] as? String,
            let oprettelsesdato = jsonElement["oprettelsesdato"] as? String,
            let overskrift = jsonElement["overskrift"] as? String,
            let address = jsonElement["address"] as? String,
            let intro = jsonElement["intro"] as? String,
            let email = jsonElement["email"] as? String,
            let tlf = jsonElement["tlf"] as? String,
            let annonce = jsonElement["annonce"] as? String,
            let journalnr = jsonElement["journal"] as? String
        { //this never returns true and location. is never set. Why??
            location.id = id
            location.oprettelsesdato = oprettelsesdato
            location.overskrift = overskrift
            location.address = address
            location.intro = intro
            location.email = email
            location.tlf = tlf
            location.annonce = annonce
            location.journalnr = journalnr

        }

        locations.append(location)

    }

3 个答案:

答案 0 :(得分:3)

如果该行

extralabel!.text = item.oprettelsesdato // <-This is where the error is thrown 

在打开一个Optional值时,是否会发现&#34;意外发现nil&#34;错误然后原因几乎可以肯定extralabel(应该命名为extraLabel以遵循camelCase命名约定)为零。在该行设置断点并检查extralabel

答案 1 :(得分:2)

您的rowSums变量是一个可选变量。因为您没有选项说“有值”“根本没有值”< /strong>。如果您将变量定义为可选,那么要从此变量中获取值,您必须展开它。强力展开的好方法是可选绑定。这是一个例子 - :

var oprettelsesdato:String?

以这种方式尝试您的代码将解决您的问题

只需使用var oprettelsesdato:String? oprettelsesdato = "hello swift!" if let value = oprettelsesdato { println(value) } else { println("no value") } 并在 VARIABLE 中存储阵列值,然后将这些值分配给标签if let条件下。

示例 - :

if let

答案 2 :(得分:2)

根据给定的JSON id显然是Int,而不是String

var id: Int

...

if let id = jsonElement["id"] as? Int,

注意:在提供非可选的初始值设定项时,不要将属性声明为可选属性,也不要在不写入初始值设定项的情况下将其声明为laibiness alibi。 Swift的类型系统鼓励您尽可能使用非可选类型。非可选类型永远不会崩溃应用程序!