我一直在尝试在处理JSON数据时收到的数据中返回某个值,但我似乎无法获得特定值。我只能得到所有的信息。这里有更详细的问题:
代码:
class ViewController: UIViewController, NSURLConnectionDelegate {
lazy var data = NSMutableData()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
startConnection()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startConnection(){
let urlPath: String = "https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/soon2challenger?api_key=(removed my private API key for obvious reasons)"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func buttonAction(sender: UIButton!){
startConnection()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
var err: NSError
// throwing an error on the line below (can't figure out where the error message is)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println(jsonResult)
}
}
代码工作正常。这是我得到的结果。
{
soon2challenger = {
id = 43993167;
name = soon2challenger;
profileIconId = 844;
revisionDate = 1435549418000;
summonerLevel = 30;
};
}
问题在于,当我想从列表中返回某个值时,就像在id中一样,我似乎无法做到这一点。我尝试过println(jsonResult [" id"]),但这只会导致nil。
如何从列表中返回某个值?防爆。 id,name,profileIconId
答案 0 :(得分:3)
尝试使用objectForKey
,如下所示:
let inside = jsonResult.objectForKey("soon2challenger")
现在您已经解压缩了soon2challenger对象。然后,您可以轻松获得值:
print(include.objectForKey("id"))
答案 1 :(得分:0)
您正在尝试访问子数组中的值。以前的海报是正确的;获取子数组后,您可以使用数组[" id"];