【问题标题】:Populating a Table View in Swift with a JSON object在 Swift 中使用 JSON 对象填充表视图
【发布时间】:2017-06-19 22:23:34
【问题描述】:

我在这里查看了许多其他问题,但我对 Swift 还比较陌生,我很难将这些答案放到我所拥有的上下文中。

我有一个事件数据库,我想用所述事件填充一个表格视图。在我的“EventTableViewController”中,我有以下功能:

func HTTPRequestListEvent() {
    let serverURL = NSURL(string: "http://localhost:8888/public_php/Cake/index.php/event/listevent")
    let request = NSMutableURLRequest(url:serverURL! as URL)
    request.httpMethod = "POST"

    //Create a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("HTTPRequestError1=\(error)")
            return
        }

        do {
            if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject] {
                print("1")
                for (_, value) in json {
                    if let eventItem = value as? [String:AnyObject] {
                        if let eventName = eventItem["EventName"] as? String {
                            print(eventName)
                        }
                        if let eventLocation = eventItem["EventLocation"] as? String {
                            print(eventLocation)
                        }
                    }
                }
            }
        }
        catch {
            print("HTTPRequestError2=\(error)")
        }
    }
    task.resume()
}

但是,我似乎无法让 JSON 序列化工作。它没有给我一个错误,甚至没有打印出'1'。

我也不想说'print(eventName)',但这就是我目前所知道的。我想做的是做类似的事情:

    cell.eventNameLabel.text = eventName

但我不确定如何在这种情况下获取单元格详细信息。

编辑:我的 JSON 曾在其他地方工作,但对于单一数据 - 我已经能够登录并注册用户。

使用邮递员,我从我的服务器获得以下 json 数据:

[{"EventName":"Magnificent soirée","EventLocation":"热水浴缸电影院","StartDate":"2017-12-01"},{"EventName":"盛大派对","EventLocation" :"Gazeebo","StartDate":"2017-12-02"},{"EventName":"神奇事件","EventLocation":"彩虹的尽头","StartDate":"2017-02-03 "},{"EventName":"有点垃圾的聚会","EventLocation":"Dungeon","StartDate":"2090-01-04"}]

【问题讨论】:

  • 您的 JSON 很可能不是字典。
  • 你能添加一个 JSON 样本吗?
  • @rmaddy 用外行的话来说是什么意思?我该如何处理这些信息?
  • 您的代码假设 JSON 的顶层是字典。但是你的 JSON 的顶层是一个数组。

标签: ios json swift uitableview


【解决方案1】:

第一件事。您的print("1") 不起作用的原因很简单。您正在使用 if let 解包该值,如果该值为 null,则将跳过您在 if let 中的代码。在您的代码中,只需为您的 if let 添加一个 else 并进行打印,这将被打印出来。

现在回到你的问题。您的 if let 不起作用的原因是您转换 JSON 字符串的方式。从您的 JSON 字符串来看,您在顶层有一个数组。在您的代码中,您将结果转换为[String:AnyObject],这是一个字典。所以你得到 null 作为结果,因为这个转换失败了。为了解决您的问题,这是您的代码的工作示例:

let str = "[{\"EventName\":\"Magnificent soirée\",\"EventLocation\":\"Hot tub cinema\",\"StartDate\":\"2017-12-01\"},{\"EventName\":\"Splendid party\",\"EventLocation\":\"Gazeebo\",\"StartDate\":\"2017-12-02\"},{\"EventName\":\"Magical event\",\"EventLocation\":\"The end of a rainbow\",\"StartDate\":\"2017-02-03\"},{\"EventName\":\"Slightly rubbish gathering\",\"EventLocation\":\"Dungeon\",\"StartDate\":\"2090-01-04\"}]"

do {
    let data = str.data(using: .utf8)
    if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [Dictionary<String, Any>] {
        print("1")
        for oneItemInJsonArray in json {
            if let eventName = oneItemInJsonArray["EventName"] as? String {
                print(eventName)
            }
            if let eventLocation = oneItemInJsonArray["EventLocation"] as? String {
                print(eventLocation)
            }
        }
    }else{
        print("fail")
    }
}
catch {
    print("HTTPRequestError2=\(error)")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多