SwiftyJSON生成空字符串值

3
当我构建并运行以下内容时:
// Grabbing the Overlay Networks

let urlString = "https://test.sdnnw.net/networks/overlay_networks"
if let url = NSURL(string: urlString) {
   let URLRequest = NSMutableURLRequest(URL: url)
   URLRequest.setValue("token", forHTTPHeaderField: "User-Token")
   URLRequest.setValue("username", forHTTPHeaderField: "User-Auth")
   URLRequest.HTTPMethod = "GET"
   Alamofire.request(URLRequest).responseJSON { (response) -> Void in   
     if let value = response.result.value {
       let json = JSON(value)
       print(json)
     }
   }
 }

我得到了以下结果(这是正确的):
[
  {
    "uuid" : "c8bc05c5-f047-40f8-8cf5-1a5a22b55656",
    "description" : "Auto_API_Overlay",
     "name" : "Auto_API_Overlay",
  }
]

当我构建并运行以下代码时:
// Grabbing the Overlay Networks

let urlString = "https://test.sdnnw.net/networks/overlay_networks"
if let url = NSURL(string: urlString) {
  let URLRequest = NSMutableURLRequest(URL: url)
  URLRequest.setValue("token", forHTTPHeaderField: "User-Token")
  URLRequest.setValue("username", forHTTPHeaderField: "User-Auth")
  URLRequest.HTTPMethod = "GET"
  Alamofire.request(URLRequest).responseJSON { (response) -> Void in    
    if let value = response.result.value {
      let json = JSON(value)
      print(json["name"].stringValue)
      print(json["description"].stringValue)
      print(json["uuid"].stringValue)
    }
  }
}

我收到空输出 - 没有null, nil, 或 [:], 就是空白。已经查看了SwiftyJSON和这里,并没有找到任何能解释为什么stringValue未正确工作的东西(可能我使用的关键词不正确?)。非常感谢您提供的反馈,帮助我找出错误所在。

stringValue 是一个可选项。尝试使用字符串并进行检查。 - Mtoklitz113
SwiftyJSON其实并不那么"Swifty"。当您尝试解析不存在的值时,您不会得到一个可选项,而是会得到一个空值。确实,这将防止应用程序崩溃,但它使查找错误变得更加困难了一些。 - Sulthan
感谢Dershowitz123和Sulthan的建议!最好的祝福! - techiejs
1个回答

2
在JSON中,[]字符表示数组,{}表示字典。
你的JSON结果:

[ { "uuid" : "c8bc05c5-f047-40f8-8cf5-1a5a22b55656", "description" : "Auto_API_Overlay", "name" : "Auto_API_Overlay", } ]

是一个包含字典的数组。
例如,使用循环获取内容。
使用SwiftyJSON时,使用元组(SwiftyJSON对象的第一个参数是索引,第二个参数是内容)进行循环:
for (_, dict) in json {
    print(dict["name"].stringValue)
    print(dict["description"].stringValue)
    print(dict["uuid"].stringValue)
}

当使用以Value结尾的SwiftyJSON属性时要小心,因为它们是非可选的getter(如果值为nil,则会崩溃)。而可选的getter没有Value

for (_, dict) in json {
    if let name = dict["name"].string,
        desc = dict["description"].string,
        uuid = dict["uuid"].string {
            print(name)
            print(desc)
            print(uuid)
    }
}

感谢您抽出时间回答并解释,Eric D!它起作用了。最好的问候! - techiejs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接