簡體   English   中英

解析json數組快速返回空元素

[英]Parsing a json array returns empty elements in swift

如OOPer所建議,我將其作為一個單獨的問題發布。 這是它的擴展: JSONserialization錯誤

我從讀取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選項從不為真。 怎么了?

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)

    }

如果行

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

是一個引發“在展開一個可選值時意外發現nil”的錯誤,則原因幾乎可以肯定是extralabel (應遵循camelCase命名約定應命名為extraLabel)為nil。 在該行設置一個斷點,然后檢查extralabel

您的var oprettelsesdato:String? variable是一個可選變量。並且因為您沒有任何可選變量說“有一個值”“根本沒有一個值” 。如果將變量定義為可選變量,則必須從該變量獲取值解開 it.And好辦法,迫使解包都是可選的約束力 。這里是一個示例- :

var oprettelsesdato:String?

  oprettelsesdato = "hello swift!"

  if let value = oprettelsesdato
  { 

   println(value)

  }
else

{

println("no value")

}

以這種方式嘗試您的代碼可以解決您的問題

if let使用,並以可變的方式存儲數組值,然后if let條件if let分配給您的標簽

例-:

if let value =  item.oprettelsesdato
{
extralabel.text = value
}

else
{
print("no value")
}

根據給定的JSON id顯然是Int ,而不是String

var id: Int

...

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

注意:提供非可選的初始化程序時,請勿將屬性聲明為可選屬性,也不要將懶惰的聲明聲明為不編寫初始化程序。 Swift的類型系統鼓勵您盡可能使用非可選類型。 非可選類型將永遠不會使應用程序崩潰!

暫無
暫無

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

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