Here I want to parse JSON via url. This is what actual JSON data available on url. So I need to parse it and read in my app using Alamofire. But I \'m unable to do it.
You should use SwiftyJson, which is a library for json parsing, very usefull with Alamofire
In your case you can do something like this with swiftyJson :
//Array & Dictionary
var jsonArray: JSON = [
"main": ["date": "2017-01-11", "USDARS": "15.8302"]
]
let dateString = jsonArray["main"][0]["date"].string
print(dateString) = "2017-01-11"
@IBAction func btnget(_ sender: UIButton) {
let urlpath : String = "http://202.131.123.211/UdgamApi_v4/App_Services/UdgamService.asmx/GetAllTeacherData?StudentId=2011111"
let url = URL(string: urlpath)
var urlrequest = URLRequest(url: url!)
urlrequest.httpMethod = "GET"
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlrequest) { (data, response, error) in
do {
guard let getResponseDic = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print(getResponseDic as NSDictionary)
let dic = getResponseDic as NSDictionary
let msg = dic.object(forKey: "message")
print(dic)
//let arrObj = dic.object(forKey: "teacherDetail") as! NSArray
//print(arrObj)
//let arr = dic.value(forKey: "TeacherName")as! NSArray
print(((dic.value(forKey: "teacherDetail") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "TeacherName") as! String)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
// print("The title is: " + todoTitle)
} catch {
print("error trying to convert data to JSON")
return
}
} task.resume()
}
Top level json is [String:Any]
and main is an array i.e. [[String:String]]
Alamofire.request("myurl") .responseJSON { response in
if let result = response.result.value as? [String:Any],
let main = result["main"] as? [[String:String]]{
// main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array
for obj in main{
print(obj["USDARS"])
print(obj["date"])
}
}
}