【问题标题】:How do I get a value from a JSON 2 dimensional structure (nested dictionaries)?如何从 JSON 二维结构(嵌套字典)中获取值?
【发布时间】:2014-09-04 08:21:23
【问题描述】:

我很难从二维 JSON 结构中获取值并将其放入 TableView。 我使用 AFNetworking 来获取 JSON 数据。此代码构建在 Xcode 6 beta 7 中:

func apiConnetion() {
        var result: NSArray = []
        manager.GET("https://example.com/",
            parameters: nil,
            success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
                result = responseObject as NSArray
                println(result)
                dispatch_async(dispatch_get_main_queue(), {
                    self.commentData = result
                    self.commentTableView!.reloadData()
                })

            },

            failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
                println("error")
                println(" \(error.localizedDescription ) ")

        })

    }

println(result) 打印出这样的结构:

{
"id" = 1;
"name" = "Test1";
"category" =
           "id" = 1;
           "name" = "justtest";
}
{
"id" = 2;
"name" = "Test2";
"category" =
         "id" = 2;
         "name" = "justtest1";
}

如何获取类别名称?

【问题讨论】:

    标签: json xcode swift tableview afnetworking


    【解决方案1】:

    您有一个NSArray,其中包含两个条目。在cellForRowAtIndexPath 中使用indexPath.row 选择正确的条目。这将返回一个字典。选择与返回NSDictionary? 的“类别”相对应的值,因为如果键不存在,字典访问总是返回可选值。使用? 来解开它。 ?! 更安全,如果 "category" 不是键,则尝试打开 nil 会崩溃。现在查找返回NSString? 的“名称”。最后使用 nil 合并运算符 来获取字符串或如果“类别”或“名称”不是有效键则为空字符串。

    let name = result[indexPath.row]["category"]?["name"] ?? ""
    

    【讨论】:

      猜你喜欢
      • 2016-08-19
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多