我在尝试访问JSON字典中的字符串时遇到问题,这是JSON数据,我正在尝试访问的字符串是“链接”值:
channels = (
{
social = {
facebook = {
"facebook_id" = 47360808996;
link = "https://www.facebook.com/CBS";
};
twitter = {
link = "https://twitter.com/CBS";
"twitter_id" = 97739866;
};
};
}
);
这是我创建的自定义对象,它不断给我一个错误
“Type”(键:字符串,值:AnyObject)'没有下标成员“
class SocialInfo: NSObject, Mappable {
var facebook: String?
var facebookDict: String?
required init?(map: Map) {
}
func mapping(map: Map) {
///transforms string to dictionary [string: anyobject] - only used for specific JSON data name: (facebook) - (link)
let facebookTransform = TransformOf<String, [String: AnyObject]> (fromJSON: { (value: [String: AnyObject]?) -> String? in
if let value = value {
for dict in value {
if let social = dict["social"] as? NSDictionary {
if let fb = social["facebook"] as? [String: AnyObject]{
if let fbLink = fb["link"] as? String{
return fbLink
}
}
}
}
}
return nil
}, toJSON: { (value: String?) -> [String: AnyObject]? in
return nil
})
facebookDict <- (map["channels"], facebookTransform)
facebook <- map["link"]
}
}
这是我的JSON调用函数来获取信息:
func getSocialInfo (_ completion: (([SocialInfo]) -> Void)?) {
Alamofire.request("\(baseURL)/\(apiKey)/show/950", method: .get, encoding: JSONEncoding.default).responseArray { (response: DataResponse<[SocialInfo]>) in
if let channelsResponse = response.result.value {
completion?(channelsResponse)
}
}
}
作为参考,我使用NSURLSession从一个工作项目中重新创建了这个,下面的代码可以工作:
if let channels = jsonResult["channels"] as? [[String:AnyObject]], !channels.isEmpty {
let channel = channels[0] // now the compiler knows it's [String:AnyObject]
let social = channel["social"] as? NSDictionary
let facebookDict = social!["facebook"] as? [String:AnyObject]
let facebook = nullToNil(facebookDict!["link"]) as? String ?? "N/A"
let twitterDict = social!["twitter"] as? [String:AnyObject]
let twitter = nullToNil(twitterDict!["link"]) as? String ?? "N/A"
答案 0 :(得分:0)
我假设您使用Swift 3,因为Swift 2已被弃用。
在Swift 3中解析JSON时,应该避免使用NSDictionary
和AnyObject
。只需在任何地方使用[String: Any]
。