Swift将JSON解析为表格视图

时间:2019-03-06 16:20:06

标签: ios json swift

我似乎无法弄清楚如何将json解析为表格视图,对于Swift和iOS开发我还是很陌生,所以有些东西对我来说是陌生的。

我遵循了本指南:https://www.hackingwithswift.com/read/7/1/setting-up使其工作正常,只是无法弄清楚如何将json正确解析为“表视图”。我从url / api获取我的json,并成功将其打印到控制台中。

我的json的示例是:

groupby

我从https://app.quicktype.io/?l=swift

获得了这些结构
   user_id  item_tag_ids  item_timestamp
0   406225          7271      1483229353
1   406225          1183      1483229350
2   406225          5930      1483229350
3   406225          7162      1483229350
4   406225          7271      1483229350

所以我的问题是,如何在每个表行单元格的未确认数组中解析“通知”中的“标题”和“正文”?

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

然后您可以做

import random
nb_interval=4
length=5
limit_low=0
limit_high=300

for x in range(nb_interval):
    number = random.randint(limit_low,limit_high-length)
    print [number, number + length]

之后,您可以轻松地将var notificationArr = [Notification]() do { let res = try JSONDecoder().decode(JSONSource.self,from:data) notificationArr = res.unackd.map { $0.notification } } catch { print(error) } 用作表dataSource数组

答案 1 :(得分:0)

我认为AckdUnackd数组内部具有相同的类型。 所以,我想应该是这样的:

    var ackd:[Notification] = [Notification]()
    var unackd:[Notification] = [Notification]()

    func <your_func>(data:Data)->([Notification],[Notification])?{
         guard let res = try? JSONDecoder().decode(JSONSource.self,from:data) 
         else{ 
          return nil 
         }
         ackd = res["ackd"]
         unackd = res["unackd"]
         return (ackd, unackd)
    }

以及您的tableView委托中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueCell(yourCell.self, indexPath: indexPath)
    let notif = unackd[indexPath.row]
    (cell as? yourCell)?.title.text = notif.title
    return cell
}