我有一个应用程序,我试图从我创建的 API 中提取数据(该 API 基于 NODE.js、MongoDB、Express.js )
目前我正在尝试拉取对象数组,然后基于该对象数组创建一个 TableView 。例如,如果对象数组包含 4 个对象,那么 TableView 将有 4 个单元格。单击一个单元格后,我将转到另一个 View ,我可以在其中查看该对象的详细 View 。
我如何解析从 API 返回的 JSON 数据并填充表格 View 单元格?
我的问题:
目前我无法解析返回的对象数组。下面是返回的 JSON 包含的图像:
错误:
我收到以下错误:
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/