我正在使用swift从JSON检索数据。我是JSON的新手。我不知道如何检索这个嵌套值。我之前的问题是Issue raised, while retriving datas from JSON by using swift。我澄清了。这对我来说是新的。我的JSON格式如下。请指导我。
JSON响应格式:
{
"salutation": {
"id": 1,
"salutation": "Mr"
},
"firstName": "AAA",
"middleName": "BBB",
"lastName": "C",
"employeeId": "RD484",
"station": {
"id": 86,
"stationCode": null,
"stationName": "DDD",
"subDivision": null,
"address": null
},
"subDivsion": {
"id": 11,
"divisionCode": "11",
"divisionDesc": "EEE",
"division": null
}
}
//我的尝试:
var maindict = NSDictionary() //Global declaration
var session = NSURLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
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)")
self.maindict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String: AnyObject]
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// 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 {
// 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 success = parseJSON["success"] as? Int
println("Succes: \(success)")
self.dataFromJSON() //METHOD CALLING
}
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)")
//println("AUTHENTICATION FAILED")
}
}
})
task.resume()
func dataFromJSON()
{
println("Main Dict Values: \(maindict)") //PRINTING ALL VALUES
let dataArray = maindict["firstName"] as? [String:AnyObject]
println("FirstName Values: \(dataArray)") // PRINTING NIL VALUES
}
答案 0 :(得分:1)
这次您的数据结构不是以数组开头,而是使用Dictionary。你的结构就像是:
root Dictionary - > "称呼" - >字典
根词典 - > "台" - >字典
根词典 - > "的细分" - >字典
让我们说你想要访问" id" "称呼",然后:
// Just an exemple of how to download, surely you have your own way
func getJSON(url: NSURL) {
let session = NSURLSession.sharedSession()
let request = NSURLRequest(URL: url)
let task = session.dataTaskWithRequest(request){
(data, response, downloadError) -> Void in
if let error = downloadError {
println(error.localizedDescription)
} else {
var jsonError: NSError?
// cast the result as a Dictionary
if let dict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? [String: AnyObject] {
// print the dictionary to check contents
println(dict)
if let salutationDictionary = dict["salutation"] as? [String: AnyObject] {
if let id = salutationDictionary["id"] as? Int {
println(id)
}
}
}
if jsonError != nil {
println(jsonError)
}
}
}
task.resume()
}
修改强>
我的朋友,你的代码很乱......我建议你在发生错误时做一些清理,这有助于调试。无论如何,这里是您新代码的更正版本。注意第一行如何声明maindict
。此外,您对NSJSONSerialization
进行了一次不必要的调用,我对其进行了简化。注意:为了举例说明,我已将dataFromJSON
功能代码直接包含在if let parseJSON ...
内,但当然并不代表您必须这样做。
var maindict: [String: AnyObject]?
var session = NSURLSession.sharedSession()
//let parameters = ...
let request = NSMutableURLRequest(URL: your_url!)
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
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 err: NSError?
maindict = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &err) as? [String: AnyObject]
if err != nil {
println(err!.localizedDescription)
} else {
if let parseJSON = maindict {
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
println("Main Dict Values: \(maindict)")
let firstName = maindict!["firstName"] as? String
println("FirstName: \(firstName)")
}
else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
请注意细节,并通过与您的尝试进行比较来研究我的修改。我的答案已经在我自己的服务器上测试过了,所以你可以将它用作工作基础。
答案 1 :(得分:0)
最简单的方法是使用库。
1)您可以使用swiftyJSON。它使用目标C JSON解析库。 https://github.com/SwiftyJSON/SwiftyJSON
2)如果你想要一个使用纯swift解析器的库,请尝试使用JSONSwift。 github上的自述文件显示了如何从JSON文件中检索嵌套值。将它集成到项目中只需要导入一个文件。 https://github.com/geekskool/JSONSwift