I've seen a number of questions and answers addressing this. I've tried it and I can't figure it out. I've accessed my owner server's responseJSON no problem. But now I am trying to consume a 3rd party API and am having trouble. I am using Alamofire and SwiftyJSON.
let json = JSON(data: data)
this is what json looks like:
{"maxResults":50,"startAt":0,"isLast":true,"values":[{"id":1,"self":"https://stackrank.atlassian.net/rest/agile/1.0/board/1","name":"JI board","type":"scrum"},{"id":2,"self":"https://stackrank.atlassian.net/rest/agile/1.0/board/2","name":"Board2","type":"scrum"}]}
Why can't i access any of the values?
json["maxResults"].numberValue gives me '0'
json["values"].arrayValue give me an empty array []
I've seen a bunch of answers regarding the encoding etc...but I couldn't get it to work.
Here is the snippet from Alamofire showing the response format:
Alamofire.request(request).responseJSON {
response in
switch response.result {
case .success:
success(response.data!)
The object you are getting must not be a SwiftJSON object. Here's playground code that works perfectly (requires SwiftyJSON.swift to be in the Sources folder):
let jsontext = "{\"maxResults\":50,\"startAt\":0,\"isLast\":true,\"values\":[{\"id\":1,\"self\":\"https://stackrank.atlassian.net/rest/agile/1.0/board/1\",\"name\":\"JI board\",\"type\":\"scrum\"},{\"id\":2,\"self\":\"https://stackrank.atlassian.net/rest/agile/1.0/board/2\",\"name\":\"Board2\",\"type\":\"scrum\"}]}"
let data = jsontext.data(using: .utf8)!
let json = JSON(data)
print(json["maxResults"].intValue)
print(json["values"].arrayValue)
This works perfectly.
In terms of the raw data, here's what another SO question proposed:
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
let maxResults = json["maxResults"].intValue
let values = json["values"].arrayValue
print(maxResults)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}