javascript - 解析对象数组并填充表格 View 单元格 Swift

标签 javascript ios json swift mongodb

我有一个应用程序,我试图从我创建的 API 中提取数据(该 API 基于 NODE.js、MongoDB、Express.js )

目前我正在尝试拉取对象数组,然后基于该对象数组创建一个 TableView 。例如,如果对象数组包含 4 个对象,那么 TableView 将有 4 个单元格。单击一个单元格后,我将转到另一个 View ,我可以在其中查看该对象的详细 View 。

我如何解析从 API 返回的 JSON 数据并填充表格 View 单元格?

我的问题:

目前我无法解析返回的对象数组。下面是返回的 JSON 包含的图像:

enter image description here

错误:

我收到以下错误:

Error could not parse JSON: Optional([
    {
       "_id": "55d1db984f80687875e43f89",
       "password": "$2a$08$OQB/r9iIZdSFlN9L5vaiE.qILB8gP/YtlsA3S41usVnM/eXHBW9j6",
       "email": "syed.kazmi26@gmail.com",
       "__v": 0,
       "sector": "Manufacturing",
       "jobTitle": "Something 1",
       "employeeName": "Something 1"
    },

   // it displays all the data being returned in JSON response

   ])

以下是我的 SWIFT 代码:

  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

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        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
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.

            if let parseJSON = json {

            // Okay, the parsedJSON is here, let's get the value for 'success' out of it

                var sector = parseJSON["sector"] as! String
                println("Succes: \(sector)")  

            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")

            }
        }
    })

    task.resume()
}
}

最佳答案

也许您可以尝试使用 NSArray 而不是 Dictionary 并更改阅读选项。我会建议做某事。像这样:

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

希望能解决您的问题。

关于javascript - 解析对象数组并填充表格 View 单元格 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32096255/

相关文章:

javascript - 使用鼠标在 Canvas 中旋转图像

Javascript:在 Canvas 上绘制矩形在 IE 上不起作用

javascript - javascript中的自定义排序功能不起作用

iphone - 如何在 iphone 应用程序的搜索表中显示第一个词

java - 将 String 解析为 hashmap 时出现 GSON 解析错误

ios - 如何在 Swift 4 中将 Encodable 或 Decodable 作为参数传递?

javascript - 使用 javascript 在字符串中搜索单词

ios - 如何判断核心数据管理对象何时具有用于设置 toMany 关系的动态方法?

ios - 无法从源工具包生成 Swift 表示错误无法加载模块 : GoogleSignin

java - 为什么 Gson 会漂亮地打印到控制台,而不是文件?