I am attempting to use Swift 3 with (ObjectMapper) to map a players
array from a given JSON response on a cut-down class object called "Player"; but am finding it difficult to map it.
// Sample JSON
{
"_meta": {
...
},
"fixtures": [{
...
}],
"players": [{
"name": "Smith",
"id": "15475-9524",
}]
}
However, I am finding it hard to get it to understand how to make it map properly as it always complains that it needs more context.
I am wanting my JSON consumer to get me the list of players then map all the players using Object Mapper into an array.
When I use
var players : Array<Player> = Mapper<Player>().mapArray(JSONArray: res)
It complains
Type of expression is ambiguous without more context
My class is as follows
class Player: NSObject, Mappable {
var name: String?
required init?(map: Map) {
super.init()
}
// Mappable
func mapping(map: Map) {
name <- map["name"]
}
}
I am using AlamoFire to consume the JSON.
Alamofire.request(url).responseJSON(completionHandler: {
response in
switch response.result {
case .success(let JSON):
guard let res = JSON as? [String:Any] else {
print ("Can't do this")
return
}
var players : Array<Player> = Mapper<Player>().mapArray(JSONArray: res)
print (players)
break
case .failure(let error):
print("** Request failed with error: \(error) **")
break
}
I don't quite understand how to use the ObjectMapper on the array I'm wanting to fetch.
Any assistance on this would be good.
I think you are confusing JSON Dictionary with Player's array.
Try this: