我在使用 valueForKeyPath 时遇到问题,这是我获取 dataVersion 值的方式,它运行良好:
Alamofire.request(.GET, "https://www.amazon.fr/s", parameters:parameters)
.responseJSON { (_, _, JSON, _) -> Void in
let priceResult: String? = JSON?.valueForKeyPath("reponseMetadata.dataVersion") as String?
println(priceResult)
}
但是当我尝试像这样访问 url 值时,它失败了
Alamofire.request(.GET, "https://www.amazon.fr/s", parameters:parameters)
.responseJSON { (_, _, JSON, _) -> Void in
let priceResult: String? = JSON?.valueForKeyPath("preloadImages.images.url") as String?
println(priceResult)
}
这是我的Json:
{
responseMetadata: {
dataVersion: "v0.1"
},
preloadImages: {
images: [
{
url: "http://ecx.images-amazon.com/images/I/51K4P7REBKL._SL500_AC_.jpg"
}
]
}
}
我是IO的新手,所以任何帮助都将非常受欢迎!
preloadImages.images
是一个对象数组(快速语言的字典数组(,所以你的valueForKeyPath
不起作用。 不幸的是,没有任何方法可以通过 valueForKeyPath 索引数组,因此您必须不那么直接地获取它:
let string = "{ "responseMetadata": { "dataVersion": "v0.1" }, "preloadImages": { "images": [ { "url": "http://ecx.images-amazon.com/images/I/51K4P7REBKL._SL500_AC_.jpg" } ] } }"
var error : NSError?
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let json: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: .allZeros, error: &error) {
if let images = json.valueForKeyPath("preloadImages.images") as? Array<Dictionary<String,String>> {
let url = images[0]["url"]
println("url = (url)")
}
} else {
println("json failed: (error)")
}
请注意,您的 JSON 也无效,因为对象键没有用引号引起来,我假设您使用 println 转储 JSON 变量而不是显示实际的 JSON 数据。