I am trying to parse JSON using SwiftyJSON. I have been able to do everything I need successfully but I think there is a better way to do it that makes the code a little cleaner and faster using something like flatmap.
Right now I am getting the JSON data after an API call. I am using this code to parse that JSON data and put it in an array of a custom class, Contact. The custom class "Contact" has a bunch of strings in it like, "firstName," "lastName," and "phoneNumber".
Here is what the call looks like and the loop that is being used to parse the JSON in the completion handler. Is there a better way to do this using something like flatmap or something else?
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)
}
}
}
Use this map function
var allTheContacts = totalResponseArray.map { (obj) -> Contact in
let contactToAppend = Contact()
contactToAppend.firstName = obj["firstName"].stringValue
contactToAppend.lastName = obj["lastName"].stringValue
contactToAppend.phoneNumber = obj["phone"].stringValue
return contactToAppend
}
You are pretty much stuck using a map or loop function. Not much of an easier way to do it. One thing to remember if you are trying to clean up you code is that object in the swift JSON array are JSON objects. So one of the things I try to do in code is abstract the parsing of the JSON into an init function for the class it belongs to.
class Contact {
var firstName: String
var lastName: String
var phoneNumber: String
init(json: JSON) {
contactToAppend.firstName = obj["firstName"].stringValue
contactToAppend.lastName = obj["lastName"].stringValue
contactToAppend.phoneNumber = obj["phone"].stringValue
}
}
With something like this you can define you loop much simpler or you can use a simple map.
var allTheContacts = totalResponseArray.map { (obj) -> Contact in
return contact(json: obj)
}
Or the loop version
var allTheContacts = [Contact]()
for contact in totalResponseArray {
allTheContacts.append(Contact(json: contact))
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.