使用Swift 4.2创建JSON数组

时间:2019-06-10 20:19:15

标签: arrays json swift parsing swift4.2

我无法从URL提取json数据

我尝试了Alamofire,Swiftyjson和JSONDecoder,但没有得到任何数据

这是我的json url结果;

{
  "Firmalar": {
    "Firma": [
      {
        "SicilNo": "382",
        "FirmaAdi": "AYSAN PAMUK YAĞ VE YEM SANAYİ TİCARET ANONİM ŞİRKETİ",
        "Sektor": "GIDA ÜRÜNLERİ İMALATI ",
        "AcikAdres": "ACIDEREOSB MAHALLESİ FUZULİ CADDESİ NO: 2 ",
        "TelefonNo": "(322)394-5029",
        "FaksNo": "(322)394-4929",
        "EPosta": "mahmutkulak.aysanas@gmail.com",
        "WebAdresi": "www.aysanpamuk.com",
        "WebDurumu": "1",
        "TanitimFilmTR": "",
        "TanitimFilmEN": "",
        "TanitimBrosurTR": "",
        "TanitimBrosurEN": ""
      },      {
        "SicilNo": "1127",
        "FirmaAdi": "EKOVAR GERİ DÖNÜŞÜM MAKİNA İNŞAAT SAN. VE TİC. LTD. ŞTİ.",
        "Sektor": "DİĞER İMALATLAR",
        "AcikAdres": "ACIDEREOSB MAHALLESİ CUMHURİYET BULVARI NO: 26 ",
        "TelefonNo": "(312)442-1305",
        "FaksNo": "(312)442-1306",
        "EPosta": "mesut@ekovar.com.tr",
        "WebAdresi": "www.ekovar.com.tr",
        "WebDurumu": "1",
        "TanitimFilmTR": "",
        "TanitimFilmEN": "",
        "TanitimBrosurTR": "",
        "TanitimBrosurEN": ""
      }
    ]
  }
}

这是我的结构;

struct Firmalar: Codable {
    let Firma: [FirmaModel]?
}

struct FirmaModel: Codable{
    let SicilNo:String?
    let FirmaAdi:String?
    let Sektor:String?
    let AcikAdres:String?
    let TelefonNo:String?
    let FaksNo:String?
    let EPosta:String?
    let WebAdresi:String?
    let TanitimFilmTR:String?
    let TanitimBrosurTR:String?

    enum CodingKeys: String, CodingKey {
        case SicilNo="SicilNo", FirmaAdi="FirmaAdi", Sektor="Sektor", AcikAdres="AcikAdres", TelefonNo="TelefonNo", FaksNo="FaksNo", EPosta="EPosta", WebAdresi="WebAdresi", TanitimFilmTR="TanitimFilmTR", TanitimBrosurTR="TanitimBrosurTR"
    }
}

这是我的fetchData代码;

 var firmalar = [Firmalar]()
    let searchController = UISearchController()

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchFirmaData()
    }

    func fetchFirmaData(){
        let url = URL(string: "http://mobileapi.adanaorganize.org.tr/v1/firmalar")
        guard let downloadURL = url else {return}
        URLSession.shared.dataTask(with: downloadURL) { (data, response, error) in
            do{
                if error == nil {
                    self.firmalar = try JSONDecoder().decode([Firmalar].self, from: data!)
                    DispatchQueue.main.async {
                        print(self.firmalar)
                        self.tableView.reloadData()
                    }
                }
            } catch {
                print("Error While Geting Json Data: " + error.localizedDescription)
            }
            }.resume()
    }

所以我的问题是如何创建一个数组。使用swift。这是我的快速代码。我收到此错误消息:由于数据格式不正确,因此无法读取。

2 个答案:

答案 0 :(得分:0)

首先从不打印error.localizedDescription,它返回一个通用的,毫无意义的错误消息。始终仅打印error

真正的错误是

  

打算对Array进行解码,但是找到了一个字典

错误非常明显。查看JSON。根对象是字典,键Firma的值是您要查找的数组。

您必须为根对象添加另一个结构并对其进行解码

struct Root: Codable {
    let firmalar: Firmalar

    private enum CodingKeys: String, CodingKey { case firmalar = "Firmalar" }
}

struct Firmalar: Codable {
    let firma: [FirmaModel]

    private enum CodingKeys: String, CodingKey { case firma = "Firma" }
}

struct FirmaModel: Codable { ...

声明数据源数组

var firmaModel = [FirmaModel]()

并解码JSON

if error == nil {
    let result = try JSONDecoder().decode(Root.self, from: data!)
    self.firmaModel = result.firmalar.firma

将所有结构成员声明为非可选成员,并使用CodingKeys映射的小写成员,就像我建议的结构一样。

答案 1 :(得分:0)

您没有Firmalar数组,但是只有一个值,并且该值本身必须是单独的根级别结构的一部分,因此请更改

self.firmalar = try JSONDecoder().decode([Firmalar].self, from: data!)

let result = try JSONDecoder().decode(Response.self, from: data!)
self.firmalar = result.Firmalar.Firma

当然,您需要将firmalar的声明更改为

var firmalar = [FirmaModel]()

并包含根级结构

struct Response: Decodable {
    let Firmalar: Firmalar
}