I'm new to Swift and JSON and am having trouble. I have looked at all sorts of Q&A's here and tried incorporating the advice, but am failing to do so correctly.
I have the server generating JSON which is ok according to a JSON lint checker (http://jsonlint.com).
Using a browser, the response is this:
[{"PostalCode":"NW4 2JL"},{"PostalCode":"NW4 2ES"},{"PostalCode":"NW4 3XP"},{"PostalCode":"NW4 4DU"},{"PostalCode":"NW4 2HH"},{"PostalCode":"NW4 2DR"},{"PostalCode":"NW4 2DX"}]
Xcode, however, gives me this error:
Error, sorry, could not parse JSON: Optional([{"PostalCode":"NW4 2JL"},{"PostalCode":"NW4 2ES"},{"PostalCode":"NW4 3XP"},{"PostalCode":"NW4 4DU"},{"PostalCode":"NW4 2HH"},{"PostalCode":"NW4 2DR"},{"PostalCode":"NW4 2DX"}])
What baffles me, and I can find no explanation for, is the 'Optional()' part. Prior to that, the error statement is as I wrote it, on line 12 (the only message that includes the word 'sorry'). The JSON inside the '()' looks fine.
Can anyone advise what I've done wrong here, or at least where the 'Optional()' text is coming from?
This is the relevant portion of my code:
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary {
let success = json["success"] as? Int
print("Success: \(success)")
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error, sorry, could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
}