How to display NsMutable Array - ios

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"

Related

Converting String to [String : Any]

I have a string that defines an object like so:
let object = """
{
"id": 59d75ec3eee6c20013157aca",
"upVotes": NumberLong(0),
"downVotes": NumberLong(0),
"totalVotes": NumberLong(0),
"timestamp" : "\(minutesAgo(1))",
"caption": "hello",
"username": "hi",
"commentsCount": NumberLong(0),
"lastVotingMilestone": NumberLong(0),
"type": "Text"
}
"""
I need to convert it into the format [String : Any] but I'm not sure how to do this. In the past I have put the string into a json file and loaded that like this:
let data = NSData(contentsOfFile: file)
let json = try! JSONSerialization.jsonObject(with: data! as Data, options: [])
let dict = json as! [String: Any]
Anyone know how I can do this? Thanks!
Why are you doing it the complicated way in the first place? You want a dictionary, so define a dictionary.
let dict: [String: Any] = [
"id": "59d75ec3eee6c20013157aca",
"upVotes": 0,
"downVotes": 0,
...
]
Anyway, the NumberLong(0) isn't valid JSON, so that isn't going to work anyway.
In Swift 4, you can use JSONDecoder API to decode JSON data, i.e.
let object = """
{
"id": 59d75ec3eee6c20013157aca",
"upVotes": NumberLong(0),
"downVotes": NumberLong(0),
"totalVotes": NumberLong(0),
"timestamp" : "Some Value",
"caption": "hello",
"username": "hi",
"commentsCount": NumberLong(0),
"lastVotingMilestone": NumberLong(0),
"type": "Text"
}
"""
if let data = object.data(using: .utf8)
{
if let dict = try? JSONDecoder().decode([String: Any].self, from: data)
{
}
}

How to pasre JSON (dictionary and array) using the new Swift 3 and Alamofire

Can any one suggest and send me sample code for fetching JSON response. Few APIs I am getting data in the form of the NSDictionary and few APIs I am getting data in the form of NSArray.
This is my API request with Alamofire.
APIManager.sharedInstance.getTeacherProfileDataFromURL(){(userJson)-> Void in
let swiftyJsonVar = JSON(userJson)
print("userJson userJson userJson userJson",userJson)
print("swiftyJsonVar",swiftyJsonVar)
}
1) API WITH JSON ARRAY OF DATA
{
"status": 1,
“student”: [
{
"name": "Sprouse",
"subject": [
“english”
],
"personal_email": "",
"school_email": "cole.sprouse483#demo.in",
"phone": "9665478544",
"class_teacher": false,
"image": "/assets/default_male.png"
},
{
"name": “elen”,
"subject": [
"Social Science"
],
"personal_email": "",
"school_email": "elena.gilbert564#demo.in",
"phone": "9066260799",
"class_teacher": false,
"image": "/assets/default_female.png"
},
],
"message": "Details fetched successfully."
}
2) ANOTHER API WITH JSON DICTIONARY OF DATA
{
"status": 1,
"dashboard": {
"announcement": [
{
"title": "Independence Day Celebration",
"posted_on": "13 August, 2017"
}
],
"student": {
"attendance_percent": 100,
"assignment": [
{
"title": "Alphabets in HINDI",
"end_date": "13/09/2017",
"subject": "Hindi",
"teacher_name": "Bonnie Bennette"
}
],
"leave_apply": 13
},
"image": "/system/images/86/j1f9DiJi_thumb.jpg?1504593436"
},
"message": "Details fetched successfully."
}
1) API WITH JSON ARRAY OF DATA
let swiftyJsonVar = JSON(userJson)
let array : [[String : String]] = swiftyJsonVar["student"]
This will give you an array of dictionaries or key-values of student.
Further you can get another value from the array like that
let name : String = array[0]["name"]
2) ANOTHER API WITH JSON DICTIONARY OF DATA
let swiftyJsonVar = JSON(userJson)
let dictionary : [[String : String]] = swiftyJsonVar["dashboard"]
This will give you an array of dictionary or key-value of dashboard.
let array : [[String : String]] = dictionary["announcement"]
This will give you the array of announcement and next you can get the further values like this
let name : array = array[0]["title"]
i have resolved my issue long back , posting lately this is my answer it may helpful for other thats why i am posting here.
if data is in the form of array.
DispatchQueue.main.async {
TeacherAPIManager.sharedInstance.FetchTeacherStudentAttendanceDataFromURL(){(attendanceJson)-> Void in
print("observationInfo --",attendanceJson)
let swiftyAttendanceJsonVar = JSON(attendanceJson)
let observation = swiftyAttendanceJsonVar["list"].rawString()!
let jsonData = observation.data(using: .utf8)!
let array = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Array< Any>
for observationVar in array!{
let totlDic = NSMutableDictionary()
let dic = observationVar as! Dictionary<String,Any>
}
}
if data is in the form of dictionary. just replace this below of line code in above function array line.
let dictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as! Dictionary<String, Any>

Get value from server reponse swift

I am new to Swift,
I want to get value of latitude and longitde from server reponse.
How do i get the value?
Here is my code:
WebServiceHelper.sharedInstance.makeWebServiceCall(urlAddress: "http://jsonplaceholder.typicode.com/users/1", requestMethod: "GET", params: ["Key" : "value"], Success: { (JSON:Any) in
print("Success Received data is: \(JSON)")
}, Error: { (JSON:Any) in
print("Error Received data is: \(JSON)")
}) { (JSON:Any) in
print("Header Received data is: \(JSON)")
}
I am able to get server reponse Here it is:
Success Received data is: {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"latitude": "-37.3159",
"longitude": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
How do i get?
you can try like this to get lat long :
if let result = JSON as? [String:AnyObject]{
let address = result?["address"] as? [String:AnyObject]
let geo = address?["geo"] as? [String:AnyObject]
print(geo?["lng"])
print(geo?["lat"]) }

Parse JSON response using SwiftyJSON 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

Json Tableview Swift

this post follows an old post where some people helped me for a similar problem.
I currently developing an app which list user object by making an request to a webservice, which send a response in JSON in this format :
{
"objects": [
{
"id": "28",
"title": "test",
"price": "56 €",
"description": "kiki",
"addedDate": "11-07-2015",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "69330",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "1",
"subcategory_label": "Voitures",
"picture": "",
"bdd": {},
"picture_url": "http://jdl-barreme-orange.dyndns.org/WEBSERVICE/pictures/test.JPG"
},
{
"id": "27",
"title": "ferrari",
"price": "55 €",
"description": "rouge jantes",
"addedDate": "11-07-2015",
"user_id": "1",
"user_name": "CANOVAS",
"user_zipCode": "69330",
"category_id": "1",
"category_label": "VEHICULES",
"subcategory_id": "1",
"subcategory_label": "Voitures",
"picture": "",
"bdd": {},
"picture_url": "http://jdl-barreme-orange.dyndns.org/WEBSERVICE/pictures/ferrari.JPG"
}
}
I search a method to retrieve for each dictionary the value title and price and put them in a tableView.
Code I used (tableviewcontroller) :
if let jsonArray = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: nil) as? [[String:AnyObject]] {
for dict in jsonArray {
if let title = dict["title"] as? String {
println(title)
}
}
}
But it doesn't work, I put a breakpoint, and Xcode stop to interpret here :
for dict in jsonArray
Thanks for your help.
This example JSON is not valid: it lacks a ] before the last }.
But I guess this is just a pasting typo and the JSON you're using is properly formatted, so your problem is that you need to first access the objects key of your dictionary.
This key holds a value of an array of dictionaries, so we're using it as a typecast:
if let json = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: nil) as? [String:AnyObject] {
if let objects = json["objects"] as? [[String:AnyObject]] {
for dict in objects {
if let title = dict["title"] as? String {
println(title)
}
}
}
}
First we cast the result of NSJSONSerialization.JSONObjectWithData as the dictionary: [String:AnyObject], then we access the value for the objects key, then we cast this value as an array of dictionaries: [[String:AnyObject]].
Remember, with JSON format, dictionaries are formatted with {} and arrays are formatted with [].
Your example is {key:[{},{}]} so it's a dictionary holding an array of dictionaries.
Update for Swift 2.0
if let json = try? NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as? [String:AnyObject] {
if let objects = json?["objects"] as? [[String:AnyObject]] {
for dict in objects {
if let title = dict["title"] as? String {
print(title)
}
}
}
}
Try this :
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
var DataFromJSon = jsonResult["objects"] as! NSArray
for one in DataFromJSon {
var title = one["title"] as! String
println(title)
}

Resources