这是我使用的对象:
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())
}
}
最初,我有&#34; facebookLink&#34;在&#34; Facebook&#34;作为一个字符串的类,但它保持为零。然后我尝试使用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
}
}
}
答案 0 :(得分:0)
尝试将链接设置为字符串
var stringURL:String?
获取链接
stringURL <- map["link"]
将stringURL
转换为URL
if let url = URL(string: stringURL) {
// do something
}
另请注意,这不起作用,因为您特别要说facebookDictionary
= = Facebook
对象。
class Social: Mappable {
var facebookSocial: Facebook?
var twitterSocial: Twitter?
fileprivate var facebookDictionary:[AnyHashable:Any]?
fileprivate var twitterDictionary:[AnyHashable:Any]?
required init?(map: Map) {
}
func mapping(map: Map) {
facebookDictionary <- map["facebook"]
twitterDictionary <- map["twitter"]
if let _facebookDictionary = facebookDictionary,
let _twitterDictionary = wittertDictionary {
let twitterMap = Map(mappingType: .fromJSON, JSON: _twitterDictionary)
let facebookMap = Map(mappingType: .fromJSON, JSON: _facebookDictionary)
/// Here you can initiate both object using map.
facebookSocial = Facebook(map: facebookMap)
twitterSocial = Twitter(map: twitterMap)
/// If you want to use mapping function, set this as:
facebookSocial = Facebook()
twitterSocial.mapping(map: twitterMap)
facebookSocial = Facebook()
twitterSocial.mapping(map: twitterMap)
}
}
}
由于您没有使用社交字典创建新地图,因此两个对象始终为nil
社交相同,首先从社交map
创建dictionary
。