how to retrive JSON data by using swift -
i retrieving datas json using swift. new json. don't how retrieve nested values. previous question issue raised, while retriving datas json using swift . got clarified. new me. json format below. kindly guide me.
json response formats:
{ "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 } }
//my attempt:
var maindict = nsdictionary() //global declaration var session = nsurlsession.sharedsession() //now create nsmutablerequest object using url object let request = nsmutableurlrequest(url: url!) request.httpmethod = "post" //set http method post var err: nserror? request.httpbody = nsjsonserialization.datawithjsonobject(parameters, options: nil, error: &err) // pass dictionary nsdata object , set 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) [string: anyobject] var err: nserror? var json = nsjsonserialization.jsonobjectwithdata(data, options: .mutableleaves, error: &err) as? nsdictionary // did jsonobjectwithdata constructor return error? if so, log error console if(err != nil) { println(err!.localizeddescription) let jsonstr = nsstring(data: data, encoding: nsutf8stringencoding) //println("error not parse json: '\(jsonstr)'") } else { // jsonobjectwithdata constructor didn't return error. but, should still // check , make sure json has value using optional binding. if let parsejson = json { // okay, parsedjson here, let's value 'success' out of var success = parsejson["success"] as? int println("succes: \(success)") self.datafromjson() //method calling } else { // woa, okay json object nil, went worng. maybe server isn't running? let jsonstr = nsstring(data: data, encoding: nsutf8stringencoding) println("error not parse json: \(jsonstr)") //println("authentication failed") } } }) task.resume() func datafromjson() { println("main dict values: \(maindict)") //printing values let dataarray = maindict["firstname"] as? [string:anyobject] println("firstname values: \(dataarray)") // printing nil values }
your data structure not begin array time, dictionary. structure is:
root dictionary -> "salutation" -> dictionary
root dictionary -> "station" -> dictionary
root dictionary -> "subdivsion" -> dictionary
let's want access "id" of "salutation", then:
// exemple of how download, surely have 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 result dictionary if let dict = nsjsonserialization.jsonobjectwithdata(data, options: nil, error: &jsonerror) as? [string: anyobject] { // print dictionary 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() }
edit:
my friend, code mess... suggest cleaning when you've got errors, helps debug. anyway, here's corrected version of new code. pay attention how maindict
declared on first line. also, had 1 unnecessary call nsjsonserialization
, simplified it. note: sake of example, i've included datafromjson
function code directly inside if let parsejson ...
, of course doesn't mean have same.
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 not parse json: \(jsonstr)") } } }) task.resume()
please pay attention details , study modifications comparing attempt. answer has been tested on own server , works, can use working base.
Comments
Post a Comment