SwiftyJSON 生成空白字符串值

SwiftyJSON producing blank string values

当我构建并运行以下内容时:

// 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)
    }
  }
}

我得到空白输出 - 没有 nullnil[:],只是空白。在 SwiftyJSON 和此处进行了搜索,但没有发现任何可以解决 stringValue 无法正常工作的原因(也许我正在使用不正确的关键字进行搜索?)。非常感谢关于我做错了什么的反馈。

在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)
}

小心 SwiftyJSON propertiesValue 结尾,因为它们是 非可选的 吸气剂(如果值为 nil,它将崩溃)。 optional 吸气剂没有 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)
    }
}