如何通过使用检索 JSON 数据swift

发布时间: 2017/3/5 2:26:26
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我从 JSON 检索数据,通过使用 swift 。我是新到 JSON。我不知道如何检索此嵌套的值。我刚才的问题是提出,同时通过使用 JSON 中获取数据的问题 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
    }

解决方法 1:

您的数据结构不开始用数组这一次,而是用一本字典。您的结构就像是︰

-"称呼"-词典 > 根词典
-"站"-词典 > 根词典
-"细分"-词典 > 根词典

比如说你想要访问的"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()

请注意细节,通过与您尝试比较研究我修改。我的回答已经过测试的我自己的服务器和它的作品,所以你可以使用它作为工作的基础。

赞助商