我正在尝试使用带有 ( ObjectMapper ) 的 Swift 3 来映射 players
来自名为“Player”的简化类对象的给定 JSON 响应的数组;但我发现很难对其进行映射。
// Sample JSON
{
"_meta": {
...
},
"fixtures": [{
...
}],
"players": [{
"name": "Smith",
"id": "15475-9524",
}]
}
但是,我发现很难让它理解如何正确映射它,因为它总是提示它需要更多上下文。
我希望我的 JSON 使用者为我获取玩家列表,然后使用 Object Mapper 将所有玩家映射到一个数组中。
当我使用
var players : Array<Player> = Mapper<Player>().mapArray(JSONArray: res)
它提示
Type of expression is ambiguous without more context
我的类如下
class Player: NSObject, Mappable {
var name: String?
required init?(map: Map) {
super.init()
}
// Mappable
func mapping(map: Map) {
name <- map["name"]
}
}
我正在使用 AlamoFire 来使用 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
}
我不太明白如何在我想要获取的数组上使用 ObjectMapper。
在这方面的任何帮助都会很好。
最佳答案
我认为您将 JSON 字典与播放器数组混淆了。
试试这个:
guard let res = JSON as? [String:Any] else {
print ("res:Can't do this")
return
}
guard let json_players = res["players"] as? [[String:Any]] else {
print ("json_players:Can't do this")
return
}
var players : Array<Player> = Mapper<Player>().mapArray(JSONArray: json_players)
关于arrays - Swift ObjectMapper 在没有更多上下文的情况下不断返回模棱两可,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41319158/