【问题标题】:SwiftyJSON producing blank string valuesSwiftyJSON 产生空白字符串值
【发布时间】:2016-07-02 06:43:52
【问题描述】:

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

// 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 无法正常工作的东西(也许我正在使用不正确的关键字进行搜索?)。非常感谢一些关于我做错了什么的反馈。

【问题讨论】:

  • stringValue 是可选的。尝试使用字符串并检查。
  • SwiftyJSON 实际上并非如此swifty。当您尝试解析一个不存在的值时,您不会得到一个可选值,而是一个空值。没错,这将防止应用程序崩溃,但它会使查找错误变得有点困难。
  • 感谢 Dershowitz123 和 Sulthan 的提示!最好的问候!

标签: json swift alamofire swifty-json


【解决方案1】:

在 JSON 中,[] 字符用于数组,{} 用于字典。

您的 JSON 结果:

[ {“uuid”:“c8bc05c5-f047-40f8-8cf5-1a5a22b55656”,“描述”:“Auto_API_Overlay”,“名称”:“Auto_API_Overlay”,}]

是一个包含字典的数组。

例如,通过循环获取内容。

使用 SwiftyJSON,使用元组循环(SwiftyJSON 对象的第一个参数是索引,第二个参数是内容):

for (_, dict) in json {
    print(dict["name"].stringValue)
    print(dict["description"].stringValue)
    print(dict["uuid"].stringValue)
}

注意SwiftyJSON propertiesValue 结尾,因为它们是非可选 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!有效。最好的问候!
猜你喜欢
  • 2015-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
相关资源
最近更新 更多