Converting JSON to array in Swift 2
You can use this function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { if let data = text.dataUsingEncoding(NSUTF8StringEncoding) { do { return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject] } catch let error as NSError { print(error) } } return nil}
and then you can read the array like this:
if let dict = convertStringToDictionary(jsonText) { let array = dict["headings"] as? [String]}
I would suggest using AlamofireObjectMapper. The library lets you you map objects from json easily and if combined with Alamofire can cast and return your object on the server response. The object mapping itself should look like this in your case
class CustomResponseClass: Mappable { var headings: [String]? required init?(_ map: Map){ } func mapping(map: Map) { headings <- map["headings"] }}
This way you decouple the logic of mapping and parsing json from your tableViewController.
Alternatively, You can use JSON parsing libraries like Argo or SwiftyJSON, which were created to simplify the JSON parsing. They are both well tested and will handle edge cases for you, like missing parameters in the JSON responses etc.
An example using Argo:
Assuming the JSON response has this format (from Twitter API)
{ "users": [ { "id": 2960784075, "id_str": "2960784075", ... }}
1- Create a Swift class to represent the response
Note that Response
is a class that contains an array of User
which is another class not shown here, but you get the point.
struct Response: Decodable { let users: [User] let next_cursor_str: String static func decode(j: JSON) -> Decoded<Response> { return curry(Response.init) <^> j <|| "users" <*> j <| "next_cursor_str" }}
2- Parse the JSON
//Convert json String to foundation objectlet json: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: [])//Check for nil if let j: AnyObject = json { //Map the foundation object to Response object let response: Response? = decode(j)}
An example using Swifty
As explained in the official documentation:
1- Convert JSON string to SwiftyJSON object
if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { let json = JSON(data: dataFromString)}
2- Access specific element
If data is an array then use the index
//Getting a double from a JSON Arraylet name = json[0].double
If data is a dictionary then use the key
//Getting a string from a JSON Dictionarylet name = json["name"].stringValue
2'- Loop over the elements
Array
//If json is .Array//The `index` is 0..<json.count's string valuefor (index,subJson):(String, JSON) in json { //Do something you want}
Dictionary
//If json is .Dictionaryfor (key,subJson):(String, JSON) in json { //Do something you want}