使用 SwiftyJSON 循环遍历 JSON

Looping through JSON with SwiftyJSON

我正在尝试使用 SwiftyJSON 遍历 JSON 值,以便在 UIAlertController 中显示它们。

在我使用 Alamofire 的 API 调用中,我使用

返回一些 JSON 数据
if((responseData.result.value) != nil) {

 let json = JSON(responseData.result.value!)
 let token = json["api_token"].string

 response(token: token, errorVal: json)

} else {
  return
}

然后在我的 VC 中,我将该数据用于:

if let errorVal = errorVal {

var errorMessages = ""

for (_,subJson):(String, JSON) in errorVal {

   errorMessages = errorMessages + String(subJson) + "\n"
 }

}

errorVal 正在返回:

{
  "email" : [
    "The email field is required."
  ],
  "password" : [
    "The password field is required."
  ]
}

errorMessages

[
"The email field is required."
]
[
"The password field is required."
]

但我希望 errorMessages 显示这个:

The email field is required
The password field is required

如何遍历 JSON 并只获取值?

你可以使用这样的东西:

var newMessage = String(subJson).stringByReplacingOccurrencesOfString("[", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    newMessage = newMessage.stringByReplacingOccurrencesOfString("]", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    errorMessages = errorMessages + newMessage + "\n"

由于subJson是字符串数组,所以取第一个。

if let errorVal = errorVal {
    var errorMessages = ""

    for (_,subJson):(String, JSON) in errorVal {
        // Looks like subJson is an array, so grab the 1st element
        let s = subJson[0].string
        errorMessages = errorMessages + s + "\n"
    }

}