Barry O'Reilly Barry O'Reilly - 1 month ago 63
iOS Question

How to parse Json object in swift 3

Hi my question is related to json object. i have this link "http://ip-api.com/json" and this link gives the details of your IP Address. i only need to print IP Address from this json file in swift 3. i am very new might be my question is basic but i need some help to sort out my project. so for i have done like below.

let requestURL: NSURL = NSURL(string: "http://ip-api.com/json")!

let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: requestURL as URL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest as URLRequest) {
(data, response, error) -> Void in

let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode

if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")

do{

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:AnyObject]

if let stations = json["city"] as? [[String: AnyObject]] {



for station in stations {

if let name = station["regionName"] as? String {

self.names.append(name)
print("this is query\(name)")

}
else{
print ("no ip address is found")
}

}

}

}
catch {
print("Error with Json: \(error)")
}

}
}

task.resume()


many thanks in advance.

Answer

The IP address is the value for key query on the top level of the JSON

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let query = json["query"] as? String {
  print(query)
}

In Swift 3 the type of a JSON dictionary is [String:Any]

PS: You don't need a URL request for this task, pass the URL directly and use the native structs URL (and URLRequest)

let requestURL = URL(string: "http://ip-api.com/json")!
...
let task = session.dataTask(with: requestURL) {
Comments