我想解析使用SwiftyJSON的JSON。我已经能够成功地完成所有我需要的功能,但我认为有更好的方法可以使代码更简洁,更快速地使用像flatmap这样的东西。使用swiftyjson无循环解析JSON
现在我正在获取API调用后的JSON数据。我正在使用此代码来解析该JSON数据,并将其放入自定义类Contact的数组中。自定义类“Contact”中有一串字符串,如“firstName”,“lastName”和“phoneNumber”。
以下是调用的样子,以及用于在完成处理程序中解析JSON的循环。有没有更好的方法来使用平面地图或其他东西来做到这一点?
Alamofire.request(url, method: .get).responseJSON{ response in
switch response.result {
case .success(let value):
let swiftyJsonVar = JSON(response.result.value!)
let totalResponseArray = swiftyJsonVar.arrayValue
var allTheContacts = [Contact]()
for contact in 0 ..< totalResponseArray.count{
let itterateArray = totalResponseArray[contact] //singleRetailer
let contactToAppend = Contact()
contactToAppend.firstName = itterateArray["firstName"].stringValue
contactToAppend.lastName = itterateArray["lastName"].stringValue
contactToAppend.phoneNumber = itterateArray["phone"].stringValue
allTheContacts.append(contactToAppend)
}
}
}