2016-02-09 3 views
2

Я пытаюсь получить доступ к вложенным результатам JSON, используя swiftyJSON и Alamofire. Мое значение для печати равно нулю, и я считаю, что я не делаю этого правильно. Какими должны быть мои параметры? Я пытаюсь получить значение котировки, расположенный в http://quotes.rest/qod.jsonКак получить доступ к вложенному значению JSON с помощью Alamofire и SwiftyJSON?

func getAPI() { 
    Alamofire.request(.GET, "http://quotes.rest/qod.json", parameters: ["contents": "quotes"]) 
     .responseJSON { response in 
      if let JSON = response.result.value { 
       print(JSON["quote"]) 

      } 
    } 
} 

ответ

3

В вашем JSON quotes массив, так что если вы хотите получить доступ к quote первого объекта, который вы должны сделать это путем доступа первого объекта:

func getAPI() { 
     Alamofire.request(.GET, "http://quotes.rest/qod.json", parameters: ["contents": "quotes"]) 
      .responseJSON { response in 
       if let jsonValue = response.result.value { 
        let json = JSON(jsonValue) 
        if let quote = json["contents"]["quotes"][0]["quote"].string{ 
        print(quote) 
        } 
       } 
     } 
    } 
+0

Удивительный! Спасибо за объяснение тоже отлично работает, и я это понимаю! – bandoy123

0

Если синтаксис JSON не является правильным, так как она полностью напечатанный в любом случае вы должны заметить, что это не так.

func getAPI() { 
Alamofire.request(.GET, "http://quotes.rest/qod.json", parameters: ["contents": "quotes"]) 
    // JSON response 
     .responseJSON { response in switch response.result { 
     case .Failure(let error): 
      // got an error in getting the data, need to handle it 
      print("error calling GET, json response type :") 
      // print alamofire error code 
      let statusCode = error.code 
      print("error code json : \(statusCode)") 
      // print json response from server 
      if let data = response.data { 
       print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)") 
      } 
      // print http status code plus error string 
      print(NSHTTPURLResponse.localizedStringForStatusCode(statusCode)) 
      if let httpResponse : NSHTTPURLResponse = response.response { 
       print("HTTP Response statusCode: \(httpResponse.statusCode)") 
      } 
     case .Success(_): 
      let statusCode = (response.response?.statusCode)! 
      print("status code json : \(statusCode)") 
      print("there is a response json") 
      //print(value) 
      // parse the result as JSON, since that's what the API provides and save datas as new user in coreData 
      guard let data = response.data else { 
       print("Error parsing response data") 
       return 
      } 
      let json = JSON(data: data) 
      // access first element of the array 
      if let postContent = json["contents"]["quotes"][0]["quote"].string{ 
      // deal with json 
      } 
     } 
} 
Смежные вопросы