使用SwiftyJSON循环使用JSON

时间:2016-04-13 00:49:53

标签: ios json swift swifty-json

我正在尝试使用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并仅获取值?

2 个答案:

答案 0 :(得分:1)

你可以使用这样的东西:

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

答案 1 :(得分:1)

由于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"
    }

}