Javascript 分析对象数组并填充表视图单元格

Javascript 分析对象数组并填充表视图单元格,javascript,ios,json,swift,mongodb,Javascript,Ios,Json,Swift,Mongodb,我有一个应用程序,试图从我创建的API中提取数据(该API基于NODE.js、MongoDB、Express.js) 目前,我正在尝试提取和排列对象,然后基于该对象数组创建一个tableview。例如,如果对象数组包含4个对象,则表视图将有4个单元格。单击一个单元格,我将转到另一个视图,在那里我将能够查看该对象的详细视图 如何解析API返回的JSON数据并填充表视图单元格? 我的问题: import UIKit class SectorViewController: UIViewCon

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

目前,我正在尝试提取和排列对象,然后基于该对象数组创建一个tableview。例如,如果对象数组包含4个对象,则表视图将有4个单元格。单击一个单元格,我将转到另一个视图,在那里我将能够查看该对象的详细视图

如何解析API返回的JSON数据并填充表视图单元格?

我的问题:

  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()
}
}
目前我无法解析返回的对象数组。下面是返回的JSON所包含内容的图像:

错误:

  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()
}
}
我得到以下错误:

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代替字典,并改变阅读选项。我建议你这样做:

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

希望这能解决您的问题。

也许您可以尝试使用NSArray而不是字典,并更改阅读选项。我建议你这样做:

var json : NSArray? = nil    
json = (NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as? NSArray)!
希望这能解决你的问题。

而不是

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

var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray
因为您的响应内容是一个以[开头的数组,实际上它的元素类型是
NSDictionary
。 如果开始大括号是[{,请始终查找它

JSON数组以方括号开始和结束,JSON字典以大括号开始和结束。而不是

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

var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray
因为您的响应内容是一个以[开头的数组,实际上它的元素类型是
NSDictionary
。 如果开始大括号是[{,请始终查找它


JSON数组以方括号开始和结束,JSON字典以大括号开始和结束。

看起来您正在返回JSONP(即JSON填充在名为
可选
的函数中)。听起来对吗?@Andy不,我的代码中没有名为Optional的函数。不确定如何修复此问题。看起来您正在返回JSONP(即JSON填充在名为
Optional
的函数中)。听起来对吗?@Andy不,我的代码中没有名为Optional的函数。我不确定如何修复此问题。oops没有看到您的答案。迟到了2分钟。@Tobias谢谢您的回答。您能建议如何更改阅读选项吗?在我的帖子中已经更改了,请查看选项参数。我使用了可变容器作为阅读选项s、 它指定数组和字典被创建为可变对象。oops没有看到您的答案。迟到了2分钟。@Tobias谢谢您的回答。您能建议如何更改读取选项吗?在我的帖子中已经更改了,请仔细查看选项参数。我使用可变容器作为读取选项。它指定数组和ICtionary是作为可变对象创建的。谢谢您的回答。在进行更改后,我在下面的行var sector=parseJSON[“sector”]上出现了以下错误“AnyObject不能转换为字符串”as!String
json
是一个数组,因此您必须遍历该数组。如果您需要第一个元素,则应将
let firstDict=parseJSON[0]写入NSDictionary
。感谢您的回答。在进行更改后,我收到以下错误“AnyObject不能转换为字符串”在下一行中,var sector=parseJSON[“sector”]as!String
json
是一个数组,因此您必须遍历该数组。如果需要第一个元素,则应将
let firstDict=parseJSON[0]写入NSDictionary