Parse JSON response using SwiftyJSON iOS - ios

I am trying to parse the following JSON response to get the time and availability for particular date using SwiftyJSON.
I have successfully parsed to get the date from timeSlots.
However, I am unable to get the 'time' of particular date from the response.
{
"statusCode": 200,
"doctorDetailsList": null,
"doctorDetails": {
"id": 219,
"doctorName": "Doris Wunsch",
"qualification": "MD",
"consultationFee": 760,
"experience": 0,
"timeSlots": {
"06/07/2016": [
{
"date": 1465432200000,
"time": "6:00 AM",
"availability": true
},
{
"date": 1465452000000,
"time": "11:30 AM",
"availability": true
}
],
"06/08/2016": [
{
"date": 1465259400000,
"time": "6:00 AM",
"availability": true
},
{
"date": 1465279200000,
"time": "11:30 AM",
"availability": true
}
],
"06/09/2016": [
{
"date": 1465365600000,
"time": "11:30 AM",
"availability": true
}
]
}
},
"totalDoctors": 0,
"message": null
}
This is what I did to get the timeSlots :
let todaysSlots = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"].dictionary?.keys.sort()[0])!
in return, it's giving "06/07/2016".
How do I get time and availability?

Got the result:
let todaysDate = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"]["06/07/2016"])[0]["time"]
let isAvailable = (self.doctorProfileDetail!["doctorDetails"]["timeSlots"]["06/07/2016"])[0]["availability"]

var Data : NSMutableDictionary = NSMutableDictionary()
do {
let path: String = NSBundle.mainBundle().pathForResource("Swift", ofType: "json")!
let url: NSURL = NSURL.fileURLWithPath(path)
let req: NSURLRequest = NSURLRequest(URL: url)
let data: NSData = try NSURLConnection.sendSynchronousRequest(req, returningResponse: nil)
let json: [NSObject : AnyObject] = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! [NSObject : AnyObject]
Data = json["doctorDetails"]?.valueForKey("timeSlots") as! NSMutableDictionary
print(Data)
let time : NSMutableDictionary = Data.valueForKey("06/07/2016")?.objectAtIndex(1) as! NSMutableDictionary
let timestring = time.valueForKey("time") as! String
print(timestring)
let availability : NSMutableDictionary = Data.valueForKey("06/07/2016")?.objectAtIndex(1) as! NSMutableDictionary
let numberbool = availability.valueForKey("availability") as! Bool
print(numberbool)
you can use this code and get time and availability enjoy

Related

Getting json response but not able to parse in to label

I am getting response in json format and i have array in to array but I am not able to under stood how to print on label i saw my code here
I am getting response of business_time array value so can any one please help
func CallAPI() {
let preferences = UserDefaults.standard
let uid = "u_id"
let acctkn = "acc_tkn"
if preferences.object(forKey: uid) == nil {
// Doesn't exist
} else {
let u_id = preferences.object(forKey: uid) as! String
print(u_id)
let acc_tkn = preferences.object(forKey: acctkn) as! String
print(acc_tkn)
let userprofile = ["user_id":u_id,"access_token":acc_tkn]
SVProgressHUD.show(withStatus: "Loading...")
Alamofire.request(businessDetailByUserId, method: .post, parameters: userprofile).responseJSON
{
response in
//printing response
print(response)
let result = response.result.value
// let obj=result
if result != nil{
let data = result as! [String : AnyObject]
let userdata = data["data"] as! NSDictionary
let userTimings = userdata["business_time"]
print(userTimings)
SVProgressHUD.dismiss()
}
}
}
}
and here is my response::
{
"success": "1",
"data": {
"bus_usr_id": "12",
"fk_user_id": "88",
"fk_cate_id": "2",
"bus_name": "AutoMobiles",
"bus_logo": "https://www.kwikmypay.com/mode_share/modeshare_admin/assets/images/business/bus_uvbdt1531395509.png",
"bus_address": "404 Palladium",
"bus_email": "mihir#hemshub.com",
"bus_website": "www.hemshub.com",
"bus_desc": "All types of automobiles spare parts are available.",
"fav_status": 1,
"bus_contact_no": "9876543210",
"bus_status": "1",
"sub_cate_list": "Spare Parts",
"category": "Automobiles",
"business_time": [
{
"tbl_bus_time_id": "107",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Monday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "108",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Tuesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "109",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Wednesday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "110",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Thursday",
"start_time": "17:7",
"end_time": "23:7",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "111",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Friday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "112",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Saturday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
},
{
"tbl_bus_time_id": "113",
"fk_user_id": "88",
"fk_bus_id": "12",
"day": "Sunday",
"start_time": "17:7",
"end_time": "23:8",
"status": "1",
"created_date": "2018-07-12 11:38:29"
}
]
},
"message": ""
i want to print values of business_time array on label but i am new to swift so can any one please tell me how to print
if let jsonData = response.result.value as? [String : Any],
let userdata = jsonData["data"] as? [String: Any]
let businessJsonArray = userdata["business_time"] as? [[String: Any]] {
for businessJson in businessJsonArray {
let id = businessJson["tbl_bus_time_id"]
}
}
SVProgressHUD.dismiss()
Above pattern is old. Apple release JsonEndcoder() in swift 4 which you should try.
As you mentioned the value for key business_time is an array so you get multiple items.
Basically don't use NSDictionary and NSArray in Swift, you throw away the important type information and a JSON dictionary in Swift 3+ is always [String:Any], never [String:AnyObject]
//printing response
print(response)
//don't check for `nil`, use optional bindings for all objects
if let result = response.result.value as? [String : Any],
let userdata = result["data"] as? [String : Any],
let userTimings = userdata["business_time"] as? [[String : Any]] {
for timing in userTimings {
print(timing["start_time"] as! String)
print(timing["end_time"] as! String)
}
}
SVProgressHUD.dismiss()
As you can see in each JSON there is response sector responsible for server status (200 = success etc).
Next part is data... so basically, you have several important dictionaries (header, data). To output data without alamofire:
Write to me the response.
func CallAPI()
{
let url = URL(string: "https:// your_Address")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let _ = response, let data = data
{
let result = String(data: data, encoding: .utf8)!
print(result as NSString)
} else {
print(error as Any)
}
}
task.resume()
}

How to display NsMutable Array

When decoding JSON response from webservice I get an ouput saying:
["dataresult": <__NSArrayM 0x1c0243090>( )]
How to display / decode this NSArrayM
Any help on this would be appreciated
Below is the code
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print("JSON yet to be parsed")
if let parseJSON = json {
let myBoard = parseJSON["message"] as! [String:Any]
print("JSON parsed successfully !")
print(myBoard)
if let refResults = myBoard["dataresult"] as? [[String:String]]{
let valueArray = refResults.map {$0["Success"]!}
self.Contact = valueArray
print(self.Contact)
}
Response from the Web Service:
"message": {
"dataresult": [
{
"Success": "Success",
"OwnerName": "test shop",
"mobileno": "1231231231",
"landline": "",
"managername": "acsd acfacaf",
"managerContact": "",
"email": "test#gmail.com",
"website": "",
"address": "gggysgyysusisss",
"city": "hgyggg",
"area": "fgatsbsuhsushsu",
"pincode": "123123",
"rentowned": "Leased",
"homedelivary": "Yes",
"working_start_time": "10.00 am",
"working_end_time": "7.30 pm",
"pwd": "123123"

Swift and JSON parsing only an object not an array

I am working on a weather app that parses JSON data and sets the text of my label to the temp value of the JSON request. I got the value of id from the weather object array, but the temp is not in an array it is just an object. Can someone please tell me where I am wrong. My value is reurning nil because I am not fetching it correctly. Here is my snippet and JSON.
#IBAction func getWeather(sender: AnyObject) {
let requestURL: NSURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=MYAPPID")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("JSON Downloaded Sucessfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let today = json["weather"] as? [[String: AnyObject]] {
//this is pulling 4 key value pairs
for weather in today {
//this works
let id = weather["id"]?.stringValue
self.trumpDescription.text=id;
print(id)
//this is where I am confused it changes from an array to just an object
let temp = json["temp"] as? String
self.currentTempView.text=temp;
print(temp)
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}`
Here is the JSON:
{
"coord": {
"lon": 138.93,
"lat": 34.97
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04n"
}
],
"base": "cmc stations",
"main": {
"temp": 292.581,
"pressure": 1019.48,
"humidity": 99,
"temp_min": 292.581,
"temp_max": 292.581,
"sea_level": 1028.92,
"grnd_level": 1019.48
},
"wind": {
"speed": 5.36,
"deg": 237.505
},
"clouds": {
"all": 64
},
"dt": 1464964606,
"sys": {
"message": 0.0037,
"country": "JP",
"sunrise": 1464895855,
"sunset": 1464947666
},
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
It looks like it should be
if let main = json["main"] as? NSDictionary {
let temp = main["temp"] as! String
print(temp)
}
Instead of this:
let temp = json["temp"] as? String
Try this:
if let main = json["main"] as? [String: AnyObject] {
let temp = main[temp]?.stringValue
print(temp)
//alternatively you can try this as per your convenience of data type
let tempNew = main[temp]?.doubleValue
print(tempNew)
}

Swift IOS Reading JSON from url

On the below method, I can get the place value but not the location value. how can I get the location?
Thank you in advance!!
func searchDB(looking: String){
var urlString:String = "URLGOESHERE?q=\(looking)"
let url = NSURL(string: urlString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
}
else {
//processing data
if let arr = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? [AnyObject] {
for currPlace in arr {
println(currPlace["name"])
println(currPlace["location"])
}
}
else {
errorOccurred = true
}
}//eo potential data
})
task.resume()
}//eom
This is the result output I am getting:
Optional(Buddha-Bar)
Optional(nil)
JSON sample:
sample data:
{
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 848,
"html_attributions": [],
"photo_reference": "CnRnAAAAifUh9MiqwAgQYdwEp-EnS4e_nPQN_mPYIqdI49UKun_CZKxgtUh_ZqT8QBEqBuel9seoZvyyIVvA5-TlweEqO9_2tORg_cmTi_Cy5L_PAthdZd1_Krqbf7oJNy81RWD3brA8fzeIKJfQTMgo-AT19RIQAg5kKSqeoeedm69uhUWKvBoULDJ1-PoSgv4Lsg5y1rjU_pHm_Ng",
"width": 1919
}
],
"place_id": "ChIJRS81ac1v5kcRRUqQBmTTJJU",
"price_level": 3,
"rating": 3.7,
"reference": "CmReAAAAjJskNN69nw3gBVtqLpsX11Psr-QvK6cHPLhF-oDXAbYq7dwLn65b1svUJOLVnRgAbg4K3w7qCj9_hkXvx20q4YNR2714ZQQw89GyFGCtXAxonRh09_uvgK97DewsYRyUEhAczR_GzOvU0mmG1OZr0X3kGhQeJ1Vr3RSnI6VXyzh83W_LIcUK_g",
"types": [
"bar",
"restaurant",
"food",
"establishment"
]
},
Json data without spaces
sample data:
{
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 848,
"html_attributions": [],
"photo_reference": "CnRnAAAAifUh9MiqwAgQYdwEp-EnS4e_nPQN_mPYIqdI49UKun_CZKxgtUh_ZqT8QBEqBuel9seoZvyyIVvA5-TlweEqO9_2tORg_cmTi_Cy5L_PAthdZd1_Krqbf7oJNy81RWD3brA8fzeIKJfQTMgo-AT19RIQAg5kKSqeoeedm69uhUWKvBoULDJ1-PoSgv4Lsg5y1rjU_pHm_Ng",
"width": 1919
}
],
"place_id": "ChIJRS81ac1v5kcRRUqQBmTTJJU",
"price_level": 3,
"rating": 3.7,
"reference": "CmReAAAAjJskNN69nw3gBVtqLpsX11Psr-QvK6cHPLhF-oDXAbYq7dwLn65b1svUJOLVnRgAbg4K3w7qCj9_hkXvx20q4YNR2714ZQQw89GyFGCtXAxonRh09_uvgK97DewsYRyUEhAczR_GzOvU0mmG1OZr0X3kGhQeJ1Vr3RSnI6VXyzh83W_LIcUK_g",
"types": [
"bar",
"restaurant",
"food",
"establishment"
]
},
Adding a little formatting to the pertinent part of the data:
sample data: {
"formatted_address": "8-12 Rue Boissy d'Anglas, 75008 Paris, France",
"geometry": {
"location": {
"lat": 48.868194,
"lng": 2.321596
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/bar-71.png",
"id": "560dd225114fd10997f75ee777bad84bcb40c529",
"name": "Buddha-Bar",
It is unclear what "sample data:" means as it is not quoted, it may be something added by the print statement (my guess) in which case it is not needed to access the components.
The name would be addresses as:
["name"]
The location is in lat/lon so there will be two accesses:
["geometry"]["location"]["lat"]
["geometry"]["location"]["lon"]
In the above the applicable language syntax must be applied, in Swift there will be some pain.
See json.org for information on JSON.
After some frustration and game of thrones. the messy solution was the one below.
an alternative may be api like
https://github.com/lingoer/SwiftyJSON
func searchDB(looking: String){
var errorOccurred:Bool = false
var urlString:String = "URLGOESHERE?q=\(looking)"
let url = NSURL(string: urlString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
println(error)
errorOccurred = true
} else {
// println(response) //response from post
//processing data
let jsonObject : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)
if let statusesArray = jsonObject as? NSArray{
println("********* LEVEL 1 *******")
println(statusesArray[0])
if let aStatus = statusesArray[0] as? NSDictionary{
println("********* LEVEL 2 *******")
println(aStatus)
if let geometry = aStatus["geometry"] as? NSDictionary{
println("********* LEVEL 3 *******")
println(geometry)
if let currLocation = geometry["location"] as? NSDictionary{
println("********* LEVEL 4 *******")
println(currLocation)
println(currLocation["lat"])
println(currLocation["lng"])
}
}
}
}
else {
errorOccurred = true
}
}//eo potential data
})
task.resume()
}//eom

JSON function doesn't parse for multiple JSON data

I have a page that contains these json data :
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2015"
},
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2014"
},
and this is the code I use for parsing data :
// 1
let urlAsString = "http://192.168.1.35/ios"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
// 3
if var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
// 4
let jsonDate: String! = jsonResult["date"] as NSString
let jsonTime: String! = jsonResult["time"] as NSString
dispatch_async(dispatch_get_main_queue(), {
println(jsonDate)
})
}
})
// 5
jsonQuery.resume()
The problem is that it only works if json data to be like this:
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2015"
},
and for multiple json data it stop working.What's wrong ?
Thanks
Consider validating your JSON here.
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2015"
}
is a valid JSON.
while
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2015"
},
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2014"
}
is not.
Edit:
JSON arrays are written inside square brackets. Your JSON should be:
[
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2015"
},
{
"time": "07:08:27 AM",
"milliseconds_since_epoch": 1425539307783,
"date": "03-05-2014"
}
]
You can refer here and here for more details.

Resources