【发布时间】:2015-08-19 13:00:22
【问题描述】:
我有一个应用程序,我试图从我创建的 API 中提取数据(该 API 基于 NODE.js、MongoDB、Express.js )
目前我正在尝试提取对象数组,然后基于该对象数组创建一个表格视图。例如,如果对象数组包含 4 个对象,那么表格视图将有 4 个单元格。在单击一个单元格时,我将转到另一个视图,在那里我可以查看该对象的详细视图。
如何解析从 API 返回的 JSON 数据并填充表格视图单元格?
我的问题:
目前我无法解析返回的对象数组。下面是返回的 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()
}
}
【问题讨论】:
-
它看起来就像您正在返回 JSONP(即 JSON 填充在一个名为
Optional的函数中)。听起来对吗? -
@Andy 不,我的代码中没有名为 Optional 的函数。不知道如何解决这个问题。
标签: javascript ios json swift mongodb