2015-06-30 66 views
0

我一直在試圖返回處理JSON數據時收到的數據中的某個值,但我似乎無法獲得特定值。我只能得到所有的信息。這裏有更詳細的問題:無法返回正確的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,姓名,profileIconId

回答

3

嘗試使用objectForKey像這樣:

let inside = jsonResult.objectForKey("soon2challenger") 

現在你已經提取soon2challenger對象。然後你可以很容易的得到值:

print(include.objectForKey("id")) 
+1

謝謝!它的工作:)很好的答案。 – Nick

0

你正試圖訪問一個子數組內的值。以前的海報是正確的;獲得子數組後,你可以使用array [「id」];