如何在使用Swift的struct的帮助下将JSON数据加载到Tableview中?

时间:2019-05-15 12:58:28

标签: swift

我的场景,在我的项目中,我在struct的帮助下获得JSON数据。在这里,我可以获取所有JSON数据。现在,我需要在multiple中加载每个索引array的值,并将其加载到tableview中。

注意:我也有搜索栏-按名称搜索

我的JSON

{
    "status": 1,
    "status_code": 200,
    "message": “name list",
    "result": [
        {
            "id": 6,
            "name": "Afrikaans",
            "image": "https://www.google.com/",
            "code": "af",
            “mob_code": null
        },
        {
            "id": 8,
            "name": "Albanian",
            "image": "https://www.google.com/",
            "code": "sq",
            “mob_code": null
        }
    ]
}

我的代码

  let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                    if let error = error {
                        print("returning error", error);
                        return
                    }

                    do {
                        let result = try JSONDecoder().decode(LanguagesData.self, from:data!)
                        //print("RESPONSE:\(result)")
            } catch {
                        print(error)
                    }
                })
                task.resume()

1 个答案:

答案 0 :(得分:1)

更正json

{
    "status": 1,
    "status_code": 200,
    "message": "name list",
    "result": [{
            "id": 6,
            "name": "Afrikaans",
            "image": "https://www.google.com/",
            "code": "af",
            "mob_code": null
        },
        {
            "id": 8,
            "name": "Albanian",
            "image": "https://www.google.com/",
            "code": "sq",
            "mob_code": null
        }
    ]
}

创建实例变量

var arr = [Inner]()  

解码

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let res = try decoder.decode(Root.self,from:data)   
arr = res.result 
DispatchQueue.main.async {
  self.tableView.reloadData()
}

模型

struct Root: Codable {
    let status, statusCode: Int
    let message: String
    let result: [Inner]
}

struct Inner: Codable {
    let id: Int
    let name: String
    let image: URL
    let code: String
    let mobCode: String?
}

表数据源和委托

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! <#CellName#>
    let item = arr[indexPath.row]
    cell.student_label.text = item.name
    cell.photo.sd_setImage(with:item.image, placeholderImage: UIImage(named: "placeholder.png"))
}

测试:

    let str = """
{
    "status": 1,
    "status_code": 200,
    "message": "name list",
    "result": [{
            "id": 6,
            "name": "Afrikaans",
            "image": "https://www.google.com/",
            "code": "af",
            "mob_code": null
        },
        {
            "id": 8,
            "name": "Albanian",
            "image": "https://www.google.com/",
            "code": "sq",
            "mob_code": null
        }
    ]
}
"""

    do {


        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let res = try decoder.decode(Root.self,from:Data(str.utf8))
      print(res)
    }
    catch {

        print(error)
    }