I am currently working on an app where I need to retrieve data from an API that I built using NODE.js, MongoDB, Express.js.
My goal is to pull an array of objects from the API and create a table view based on these objects. Each cell in the table view corresponds to an object in the array. When a user taps on a cell, they should be taken to another view where they can see more details about that specific object.
How should I handle parsing the JSON data returned by the API in order to populate the table view cells?
The Issue:
I am currently facing difficulty in parsing the array of objects that is returned. Here is an image showing the structure of the JSON response:
https://i.sstatic.net/pJZkd.png
The Error Message:
Upon attempting to parse the JSON data, I encountered the following error:
Error: could not parse JSON: Optional([
{
"_id": "55d1db984f80687875e43f89",
"password": "$2a$08$OQB/r9iIZdSFlN9L5vaiE.qILB8gP/YtlsA3S41usVnM/eXHBW9j6",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="41323824256f2a203b2c28737701262c20282d6f222e2c">[email protected]</a>",
"__v": 0,
"sector": "Manufacturing",
"jobTitle": "Something 1",
"employeeName": "Something 1"
},
// the full JSON response is displayed here
])
Here is my SWIFT Code:
import UIKit
class SectorViewController: UIViewController {
@IBAction func getManufacturingBios(sender: AnyObject) {
var request = NSMutableURLRequest(URL: NSURL(string: "https://myURL/user/all")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var err: NSError?
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error: could not parse JSON: '\(jsonStr)'")
}
else {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if let parseJSON = json {
var sector = parseJSON["sector"] as! String
println("Success: \(sector)")
}
else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error: could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
}