我有一个从响应中获取的JSON数据。我想将数据显示在警报视图中。
1。这是我的消息:
"error": {
"email": [
"The email has already been taken."
],
"phone": [
"The phone has already been taken."
]
}
我的Swift代码:
let errormessage = jsonObj.value(forkey: "error")
createAlert(title: "Try again" , message: errormessage as! String)
请帮助我如何在警报中显示错误消息,这将非常有帮助
答案 0 :(得分:1)
请勿快速使用NSDictionary
。使用[String:Any]
。获取字典的所有值并加入字符串数组。并以新行作为分隔符将错误加入。
let jsonObj:[String: Any] = ["error": [
"email": ["The email has already been taken."],
"phone": ["The phone has already been taken."]]
]
if let errorMsgs = jsonObj["error"] as? [String: [String]] {
let errMsg = errorMsgs.values.map { $0.reduce("", +) }.joined(separator: "\n")
print(errMsg)
createAlert(title: "Try again" , message: errMsg)
}
答案 1 :(得分:0)
您可以这样解析json:
func jsonSerializer() {
let jsonString = """
{
"error": {
"email": [
"The email has already been taken."
],
"phone": [
"The phone has already been taken."
]
}
}
"""
let data = Data(jsonString.utf8)
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let error = json["error"] as? [String: Any] {
if let email = error["email"] as? [String], email.count > 0 {
print(email[0])
// createAlert(title: "Try again", message: email[0])
}
if let phone = error["phone"] as? [String], phone.count > 0 {
print(phone[0])
// createAlert(title: "Try again", message: phone[0])
}
}
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString!)")
}
}