Fetching and displaying data from an array of objects in a table view using Swift

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()
}
}

Answer №1

Perhaps you could experiment with utilizing an NSArray instead of a Dictionary and adjusting the reading options. One suggestion would be to implement something along these lines:

var json : NSArray? = nil    
json = (NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSArray)!

Hopefully this resolves the issue you are encountering.

Answer №2

Instead of

var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

it should be

var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray

due to the fact that the response content is an array which begins with [ and contains elements of type NSDictionary. Always check for the opening braces, whether it is [ or {.

A JSON array starts and ends with square brackets, while a JSON dictionary starts and ends with curly braces.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The password comparison process is always deemed invalid when checking between the form and database

Looking to build a secure login system using Python, Django, and MongoDB. Here's the code I've got so far: from django.shortcuts import render from pymongo import MongoClient import bcrypt def login( req ): response = { 'error': ...

Selecting databases and tables on the fly in the pg-promise API

Instead of using a hardcoded initial connection object, the pg-promise API suggests creating a dynamic connection object like this: var pgp = require('pg-promise')(); const mysqlcon = `postgres://${process.env.DB_USER}:${process.env.DB_PASSWORD}@ ...

body-parser: unable to retrieve data from the form

I'm struggling to fetch values from a form using body-parser in my user sign-up feature. The console keeps printing 'undefined' which is baffling me. I even attempted using Postman, but no luck there either. Here's the snippet of my cod ...

Posting a JSON array to a server using WebAPI/MVC

I'm currently facing an issue with sending two specific objects to the server. In my form, I have an input field and a text area. Send function SendServer() { $.ajax({ url: '/api/Service', type: "POST", ...

Adding a secret code to MongoDB

Can the string be converted into a hash using a mongo command line while adding data? I need to manually input account information and create as many users as necessary. ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

Error encountered: Parsing error with Angular $HTTP response due to an unexpected token "E

Here is an example of how to make a simple POST call using the Angular $HTTP service: authService.login = function(username, password){ var credentials = 'username=' + username + '&' + 'password=' + password ...

Tabulator's seamless text wrapping feature

var table = new Tabulator("#example-table", { layout: "fitColumns", //adjust columns to fit table width height: "69vh", responsiveLayout: "collapse", //hide columns that don't fit in the table cellVertAlign: "middle", headerSort: false, c ...

Should I make it a habit to directly manipulate my business objects with core data?

As an example, let's say I have a messaging app with classes like: ChatRoom and ChatMessage, both of which are subclasses of NSManagedObject. In the course of using the app, tasks such as searching for chat rooms, adding messages, creating ChatRooms a ...

How can you convert a decimal String to a float or double in Swift?

Currently, I am facing a challenge while attempting to convert a String like "3.9" into a Float value in Swift to properly represent it as 3.9 for use in calculations. The code I am using so far is as follows: var a:Float = (lastNumber as NSString).floatV ...

Complete only the fields specified in the Interface definition

I have been developing a shopping cart service that implements a method to add a specified JSON object to a cart object. However, only the defined fields in the IProduct interface should be populated. JSON Object { "title": "Title 1", "descriptio ...

Generate the Xpath for the mentioned href element to use with Selenium Webdriver

I need help creating the Xpath for a specific href element using Selenium webdriver with only IE browser. The HTML code I am working with is as follows: I am looking to find the Xpath for: . Can someone assist in generating the correct Xpath expression ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Utilizing jq filter or jq play to merge all key-value pairs into a single entity

I am looking to utilize jq filter to transform JSON data Here is the JSON data: { "main": [ { "firstKey": "ABCD", "id": "12345", "data": [ { "name": "first_id", ...

Efficiently storing and managing a plethora of diverse

Hello, I have developed a React application that interacts with my API by sending orders. Here's an example of the JSON data format: [ { "product_id":13, "quantity":2 }, { "product_id":12, "quantity":2 ...

Identification Sequence Number

Is there a way to set up my Mongo DB so that it generates a sequence number for an Id column? For example, starting from 1001 and incrementing by 1 each time a new row is inserted. My schema definitions are included in Node.JS, so how can I configure thi ...

I seem to be encountering an issue with my captcha function on the registration form

I am currently working on a registration form where user data will be stored in the database only if the correct captcha code is entered. If the captcha code is incorrect, it should display an error message. However, I am facing an issue where even if the ...

MongoDB is capable of storing dates in a variety of formats

Using the mongodb-java-driver along with morphia, I am saving an entity into MongoDB. The entity consists of three fields of type `java.util.Date`: `createDate`, `lastUpdateDate`, and `delDate`. https://i.sstatic.net/jFIHP.png When setting the entity&apo ...

When a function is required in the mongoose model schema file, the Mongoose.model('model_name') will result in an empty object being returned

Sorry if the title of my question is confusing, as I find it hard to articulate this issue. I have two files named matchedTransaction.js and player.js. sharedApi/player.js const MatchedTransactionModel = require('../models/matchedTransaction'); ...