我正在下载一个很好的文件。然后我试图解析这个json以从中获取一个值。这是发生错误的地方。我觉得文件下载很好。这是我到目前为止所拥有的
func parseYoutubeVideo(json : String)
{
if let data = json.dataUsingEncoding(NSUTF8StringEncoding)
{
let newJson = JSON(data: data)
//Get the youtube video from the Json data
print("Parsing Video")
self.myVideo = newJson["video"].stringValue
//load the video
print("Video parsed: " + self.myVideo)
self.myYoutubePlayer .loadWithVideoId(myVideo)
}
}
//Function to log into the server and retrive data
func downloadVideoUrl(myUrl : String)
{
print("Downloading video")
Alamofire.request(.GET, myUrl)
.authenticate(user: "admin", password: "admin")
.validate()
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
if(response.result.isSuccess == true)
{
self.parseYoutubeVideo(response.result.value!)
//self.parseYoutubeVideo(self.testConfigJson)
}else
{
//remove player from the view
self.myYoutubePlayer.removeFromSuperview()
}
}
}
这就是alamofire给我的东西
Success: true
Response String: Optional("[ {\n \"video\" : \"zKevpV_Qo7A\"\n} ]")
我是否缺少如何做到这一点或我完全错误的做法。 这就是解析json数组的方法吗?
感谢您对此提供任何帮助
答案 0 :(得分:2)
使用此代码:
let data = response.result.value!.dataUsingEncoding(NSUTF8StringEncoding)
var json: NSArray?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! NSArray
}
catch error as NSError {
print(error)
}
let video = (json[0] as! NSDictionary)["video"] as String