【发布时间】:2016-12-12 21:04:19
【问题描述】:
这是我正在使用的对象映射器:
ObjectMapper/AlamoFireObjctMapper
这是我正在使用的 JSON 数据,我正在尝试访问“链接”值:
channels = (
{
social = {
facebook = {
"facebook_id" = 47360808996;
link = "https://www.facebook.com/CBS";
};
twitter = {
link = "https://twitter.com/CBS";
"twitter_id" = 97739866;
}
}
}
)
我创建了自定义对象来表示 JSON 字典的每个级别:
class SocialInfo: Mappable {
var channels: Social?
required init?(map: Map) {
}
func mapping(map: Map) {
channels <- map["channels"]
}
}
class Social: Mappable {
var facebookSocial: Facebook?
var twitterSocial: Twitter?
required init?(map: Map) {
}
func mapping(map: Map) {
facebookSocial <- map["facebook"]
twitterSocial <- map["twitter"]
}
}
class Facebook: Mappable {
var facebookLink: NSURL?
required init?(map: Map) {
}
func mapping(map: Map) {
facebookLink <- (map["link"], URLTransform())
}
}
最初我将“Facebook”类下的“facebookLink”作为字符串,但它一直返回零。然后我尝试使用 URLTransform 将其更改为 NSURL 类型,但现在它抛出了错误:
没有更多上下文的表达类型是模棱两可的
这是我尝试检索 JSON 数据的方式:
func getSocialInfo (completionHandler: @escaping (SocialInfo?, Error?) -> ()){
Alamofire.request("\(baseURL)/\(apiKey)/show/950", method: .get, encoding: JSONEncoding.default).validate ()
.responseObject{ (response: DataResponse<SocialInfo>) in
switch response.result {
case .success:
let socialInfo = response.result.value
print("This is the social info: \(socialInfo?.channels?.facebookSocial?.facebookLink)")
completionHandler(socialInfo!, nil)
case .failure(let error):
print("Sorry there was an error: \(error)")
completionHandler(nil,error)
return
}
}
}
【问题讨论】:
标签: ios json swift alamofire objectmapper