使用 Swift 创建 JSON 数组 4.2

Create JSON Array with Swift 4.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"
    }
}

这是我的获取数据代码;

 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 。这是我的 swift 代码。我收到此错误:无法读取数据,因为它的格式不正确。

首先从不 打印error.localizedDescription,它returns 是一个通用的非常无意义的错误消息。总是只打印 error.

真正的错误是

Expected to decode Array but found a dictionary instead

错误很明显。看看JSON。根对象是一个字典,keyFirma的值就是你要找的数组

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

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

将所有结构成员声明为 non-optional 并使用 CodingKeys 映射的小写成员,就像在我建议的结构中一样。

您没有 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
}