如何使用 swift 检索 JSON 数据

how to retrive JSON data by using swift

我正在使用 swift 从 JSON 中检索数据。我是 JSON 的新手。我不知道如何检索这个嵌套值。我之前的问题是 。我得到澄清。这对我来说是新的。我的 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
    }

这次您的数据结构不是以数组开头,而是以字典开头。您的结构如下:

root Dictionary -> "salutation" -> Dictionary
root Dictionary -> "station" -> Dictionary
root Dictionary -> "subDivsion" -> Dictionary

假设您要访问 "salutation" 的 "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) 可以使用swiftyJSON。它使用 objective C JSON 解析库。 https://github.com/SwiftyJSON/SwiftyJSON

2) 如果你想要一个使用纯 swift 解析器的库,请尝试 JSONSwift。 github 上的自述文件显示了如何从 JSON 文件中检索嵌套值。将它集成到您​​的项目中只需要导入一个文件。 https://github.com/geekskool/JSONSwift