Swift: parsing dynamic JSON - ios

I am trying to parse this JSON that has a changing key for each object Im trying to find the best way to parse each object. I am very new to swift programming so any example code would be very helpful. I don't need to store all the values received just particular field such as address, streetName, image
JSON Input
{
"a000!%5362657": {
"address": "20 Ingram Street",
"streetName": "Ingram Street",
"streetNumber": "20",
"streetDirection": "N",
"unitNumber": "",
"cityName": "Forest Hills",
"countyName": "New York",
"state": "NY",
"zipcode": "11375",
"listingPrice": "$1,151,000",
"listingID": "5362657",
"remarksConcat": "From nytimes.com: In the comics, Peter Parker, the mild-mannered photojournalist who is Spider-Man's alter ego, grew up at 20 Ingram Street, a modest, two-story boarding house run by his Aunt May in the heart of Forest Hills Gardens. The address actually exists and is home to a family named Parker: Andrew and Suzanne Parker, who moved there in 1974, and their two daughters. In 1989, the family began receiving junk mail addressed to Peter Parker. We got tons of it, Mrs. Parker said yesterday. Star Trek magazines, a Discover Card in his name, and notices from them over the years calling him a good customer. There were also prank phone calls, all of which she attributed to a teenager who found it funny that we had the same last name as Spider-Man.",
"rntLse": "neither",
"propStatus": "Active",
"bedrooms": "3",
"totalBaths": "2.75",
"latitude": "40.712968",
"longitude": "-73.843206",
"acres": "0.24",
"sqFt": "2,760",
"displayAddress": "y",
"listingAgentID": "8675301",
"listingOfficeID": "lmnop",
"sample_mlsPtID": "1",
"sample_mlsPhotoCount": "39",
"parentPtID": "1",
"detailsURL": "a000/5362657",
"idxID": "a000",
"idxPropType": "Residential",
"idxStatus": "active",
"viewCount": "2",
"mediaData": [],
"ohCount": "0",
"vtCount": "0",
"featured": "n",
"image": {
"0": {
"url": "http://cdn.photos.ample_mls.com/az/20151113223546806109000000.jpg",
"caption": "17596-20"
},
"totalCount": "39"
},
"fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5362657/20-Ingram-Street-Forrest-Hills-NY-11375"
},
"a000!%5358959": {
"address": "177A Bleecker Street",
"streetName": "Bleecker Street",
"streetNumber": "177",
"streetDirection": "N",
"unitNumber": "A",
"cityName": "Greenwich Village",
"countyName": "New York",
"state": "NY",
"zipcode": "10012",
"listingPrice": "$616,000,000",
"listingID": "5358959",
"remarksConcat": "Home to Dr. Stephen Vincent Strange(Doctor Strange in Marvel comics) and his faithful bodyguard and manservant Wong. Spider-Man often visits the Doctor for help when battling those with magic powers. Features: Wong's Storage Cellar, Strange's bedchambers, guest quarters, Wong's bedchamber, Study, Meditain Chamber, Library, Storage Area for Occult Artifacts.",
"rntLse": "neither",
"propStatus": "Active",
"bedrooms": "2",
"totalBaths": "2.75",
"latitude": "40.729117",
"longitude": "-74.000773",
"acres": "0.31",
"sqFt": "206800000000",
"displayAddress": "y",
"listingAgentID": "8675301",
"listingOfficeID": "lmnop",
"sample_mlsPtID": "1",
"sample_mlsPhotoCount": "34",
"parentPtID": "1",
"detailsURL": "a000/5358959",
"idxID": "a000",
"idxPropType": "Residential",
"idxStatus": "active",
"viewCount": "6",
"mediaData": [],
"ohCount": "0",
"vtCount": "0",
"featured": "y",
"image": {
"0": {
"url": "http://cdn.photos.sample_mls.com/az/20151105214013253867000000.jpg",
"caption": "Front"
},
"totalCount": "34"
},
"fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5358959/177A-Bleecker-Street-Greenwich-Village-NY-10012"
}
}
swift viewController
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
//final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
final let urlString = "https://api.idxbroker.com/clients/featured"
#IBOutlet weak var tableView: UITableView!
var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithTask()
//self.downloadJsonWithURL()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/***********************************************************************************************/
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
/************** Get Users Accesy Key for API CALL *************************/
var key = String()
let textFieldKeyConstant = "AccessKey"
let defaults = UserDefaults.standard
if let textFieldValue = defaults.string(forKey: textFieldKeyConstant) {
key = textFieldValue
}
print(key) //accesskey debug
/******************** End Get accessKey *************************************/
/******************** Add Headers required for API CALL *************************************/
downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
downloadTask.setValue(key, forHTTPHeaderField: "accesskey")
downloadTask.setValue("json", forHTTPHeaderField: "outputtype")
downloadTask.httpMethod = "GET"
/******************** End Headers required for API CALL *************************************/
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData ?? "Default")
/******** Parse JSON **********/
/******** End Parse JSON **********/
/******** Reload table View **********/
OperationQueue.main.addOperation({
self.tableView.reloadData()
}) }).resume()
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.nameLabel.text = nameArray[indexPath.row]
cell.dobLabel.text = dobArray[indexPath.row]
let imgURL = NSURL(string: imgURLArray[indexPath.row])
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as URL?)!)
cell.imgView.image = UIImage(data: data! as Data)
}
return cell
}
/****************************************************************/
///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
vc.imageString = imgURLArray[indexPath.row]
vc.nameString = nameArray[indexPath.row]
vc.dobString = dobArray[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}

for swift3 [String:Any] it is a Dictionary with key has String and Any type in Swift, which describes a value of any type
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
print(parsedData)
} catch let error as NSError {
print(error)
}
For example :
if let info = parsedData["a000!%5362657"] as? [String : String]{
if let address = info["address"] {
print(address)
}
}
Working with JSON in Swift apple blog https://developer.apple.com/swift/blog/?id=37

Related

How to separate tableview header and cellForRowAt from same json in swift

I want to display countrycode as header of table view and after click on header venue should display. I had tried but I'm unable to achieve output as expected.
This is my json :
{
"meetings": [
{
"meetingId": 31389393,
"name": "Ludlow 20th Apr",
"openDate": "2022-04-20T12:00:00+00:00",
"venue": "Ludlow",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good"
},
{
"meetingId": 31389469,
"name": "Catterick 20th Apr",
"openDate": "2022-04-20T12:40:00+00:00",
"venue": "Catterick",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good (Good to Soft in places)"
},
{
"meetingId": 31389416,
"name": "Perth 20th Apr",
"openDate": "2022-04-20T12:50:00+00:00",
"venue": "Perth",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good to Soft (Good in places)"
},
{
"meetingId": 31389532,
"name": "Lingfield 20th Apr",
"openDate": "2022-04-20T15:15:00+00:00",
"venue": "Lingfield",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Standard"
},
{
"meetingId": 31389447,
"name": "Salisbury 20th Apr",
"openDate": "2022-04-20T15:25:00+00:00",
"venue": "Salisbury",
"eventTypeId": 7,
"countryCode": "GB",
"meetingGoing": "Good to Firm (Good in places)"
}
]
}
Here is my code which is I'm using for getting data:
struct Racing{
var countryCode:String
var venue: [String]
var races: [Races]?
}
var todayRacingArray = [Racing]()
APIClient2<RacingListBaseClass>().API_GET(Url: url, Params: noParams, Authentication: false, Progress: false, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (response) in
for item in response.meetings ?? []
{
let cc = item.countryCode
var venue = [String]()
ven.append(item.venue ?? "")
let obj = Racing(countryCode: cc ?? "", venue: venue)
self.todayRacingArray.append(obj)
}
self.otherSportsTableView.reloadData()
}) { (failed) in
}
TableView:
func numberOfSections(in tableView: UITableView) -> Int {
return self.todayRacingArray.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todayRacingArray[section].venue.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: HeaderTableViewCell.self)) as! HeaderTableViewCell
let obj = todayRacingArray[section]
cell.titleLbl.text = obj.countryCode
return cell
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: BodyTableViewCell.self)) as! BodyTableViewCell
cell.frame = tableView.bounds
cell.layoutIfNeeded()
let obj = self.todayRacingArray[indexPath.section].venue[indexPath.row]
cell.horseTitleLabel.text = obj
return cell
}
My Output My table Header After Clicking on header
I want Output like this: enter image description here After clicking on header
Please someone helpme out with this.
Updated Answer
Add a new model RaceVenue. Then modify Racing struct like below.
struct RaceVanue {
var venue: String
var races: [Race]?
}
struct Racing {
var countryCode:String
var raceVenues: [RaceVanue]
}
Modify the declaration of countryVenueDict dictionary.
var countryVenueDict: [String: [RaceVanue]] = [:]
Then modify the code when adding it to countryVenueDict dictionary. And then also modify Racing model when add it to todayRacingArray
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(RaceVanue(venue: item.venue ?? "", races: item.races))
} else {
countryVenueDict[item.countryCode ?? ""] = [RaceVanue(venue: item.venue ?? "", races: item.races)]
}
}
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, raceVenues: $0.value) }
Previous Answer
Add a dictionary to map the venue with countrycode before the declaration of todayRacingArray
var countryVenueDict: [String: [String]] = [:]
var todayRacingArray = [Racing]()
Modify the code in for loop like below.
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(item.venue ?? "")
} else {
countryVenueDict[item.countryCode ?? ""] = [item.venue ?? ""]
}
}
Then append [Racing] array to todayRacingArray by mapping the transforming the countryVenueDict by using map function.
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, venue: $0.value) }
Here is the full code
var countryVenueDict: [String: [String]] = [:]
var todayRacingArray = [Racing]()
APIClient2<RacingListBaseClass>().API_GET(Url: url, Params: noParams, Authentication: false, Progress: false, Alert: true, Offline: false, SuperVC: self, completionSuccess: { (response) in
for item in response.meetings ?? []
{
if let _ = countryVenueDict[item.countryCode ?? ""] {
countryVenueDict[item.countryCode ?? ""]?.append(item.venue ?? "")
} else {
countryVenueDict[item.countryCode ?? ""] = [item.venue ?? ""]
}
}
todayRacingArray += countryVenueDict.map { Racing(countryCode: $0.key, venue: $0.value) }
self.otherSportsTableView.reloadData()
}) { (failed) in
}

Create Search Bar that show data in dropdown menu in swift

I'm creating E-Commerce type app where user select zones from the list using textfield.
I want to that when user click on text Filed and write zone (like 55) and show dropdown all the data from the array which starting to 55 or having number of 5 in array (like 20051).
After showing all data in the form of dropdown. User select desired zone code and added in table view.
Use the code below to add search bar to UItableviewController and get searchBar on selecting UITextfield.
class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var txtName: UITextField!
var originalArr = [[String:Any]]();
var searchArrRes = [[String:Any]]()
var searching:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
//Assign delegate don't forget
txtName.delegate = self
tableView.delegate = self
tableView.dataSource = self
//my array
originalArr = [
["name": "abdul", "number": "+8800000001"],
["name": "abdin", "number": "+8800000002"],
["name": "Enamul", "number": "+8800000003"],
["name": "enam", "number": "+8800000004"],
["name": "Rafi", "number": "+8800000005"],
["name": "Ehaque", "number": "+8800000006"],
["name": "ab", "number": "+8800000007"],
["name": "Emon", "number": "+8800000008"],
["name": "enamu1", "number": "+8800000009"],
["name": "rafi", "number": "+88000000010"],
["name": "karim", "number": "+88000000011"],
["name": "radev", "number": "+88000000012"],
["name": "da", "number": "+88000000013"],
["name": "aa", "number": "+88000000014"],
["name": "rafi", "number": "+88000000010"],
["name": "karim", "number": "+88000000011"],
["name": "radev", "number": "+88000000012"],
["name": "da", "number": "+88000000013"],
["name": "aa", "number": "+88000000014"]
]
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range:
NSRange, replacementString string: String) -> Bool{
//input text
let searchText = textField.text! + string
//add matching text to arrya
searchArrRes = self.originalArr.filter({(($0["name"] as! String).localizedCaseInsensitiveContains(searchText))})
if(searchArrRes.count == 0){
searching = false
}else{
searching = true
}
self.tableView.reloadData();
return true
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//check search text & original text
if( searching == true){
return searchArrRes.count
}else{
return originalArr.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//custom cell Custom_cell
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Custom_cell
//check search text & original text
if( searching == true){
var dict = searchArrRes[indexPath.row]
cell.label_name.text = dict["name"] as? String
cell.label_number.text = dict["number"] as? String
}else{
var dict = originalArr[indexPath.row]
cell.label_name.text = dict["name"] as? String
cell.label_number.text = dict["number"] as? String
}
return cell
}
}
CustomCell Class
class Custom_cell: UITableViewCell {
#IBOutlet weak var label_name: UILabel!
#IBOutlet weak var label_number: UILabel!
}

Error in get JSON Data in swift 4.0

My JSON looks like this and data is not coming from the server:
[
{
"emp_id": "1",
"fname": "Shreya",
"lname": "Shah",
"email_id": "shreyashah#gmail.com",
"password": "shreya123",
"date_of_birth": "14/03/1995",
"gender": "Female",
"street1": "Arbudgiri Society",
"street2": "Nr.Rambaug Road",
"city": "Ahmedabad",
"zipcode": "380005",
"country": "India",
"country_code": "+91",
"phone_no": "456544545",
"emp_img": "employeeImages/shreyashah#gmail.com_services-pic2.jpg",
"emp_desig": "PHP Developer",
"emp_skills": "html,php,css,jquery,javascript",
"emp_edu": "BCA,MCA",
"emp_exp": "3years",
"emp_notice_period": "30days",
"emp_lang": "english,hindi,gujarati"
},
{
"emp_id": "2",
"fname": "Harish",
"lname": "Verma",
"email_id": "harishverma#gmail.com",
"password": "harish123",
"date_of_birth": "22/07/1994",
"gender": "Female",
"street1": "Satyam Skyline",
"street2": "Nr.Sola Cross Roads",
"city": "Ahmedabad",
"zipcode": "380005",
"country": "India",
"country_code": "+91",
"phone_no": "964783214",
"emp_img": "employeeImages/harishverma#gmail.com_services-pic2.jpg",
"emp_desig": "iOS Team Lead",
"emp_skills": "objective-c,swift",
"emp_edu": "BCA,MCA",
"emp_exp": "3years",
"emp_notice_period": "30days",
"emp_lang": "english,hindi,gujarati"
}
]
My code in VIEWCONTROLLER code where i have decoded the json and used it in my file:
import UIKit
struct EmployeeDisplayData: Decodable {
let emp_img: String
let fname: String
let emp_desig: String
let emp_exp: String
let country: String
let emp_notice_period: String
}
class UserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var mainTableView: UITableView!
let URL_GET_DATA = "http://172.16.1.22/Get-Employee-API/get-employee/"
var employeeArray = [EmployeeDisplayData]()
override func viewDidLoad() {
super.viewDidLoad()
self.mainTableView.delegate = self
self.mainTableView.dataSource = self
getEmployee()
// Do any additional setup after loading the view, typically from a nib.
// Do any additional setup after loading the view.
}
func getEmployee(){
let empURL = URL(string: "http://172.16.1.22/Get-Employee-API/get-employee/")
URLSession.shared.dataTask(with: empURL!) { (data, response, error) in
do
{
if error == nil
{
self.employeeArray = try JSONDecoder().decode([EmployeeDisplayData].self, from: data!)
for mainArr in self.employeeArray
{
DispatchQueue.main.async {
self.mainTableView.reloadData()
}
}
print("****Employee Data****\(self.employeeArray)")
}
}
catch
{
print("Error in get JSON Data Employee\(error)")
}
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return employeeArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:EMpTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EMpTableViewCell") as! EMpTableViewCell
let empData = employeeArray[indexPath.row]
cell.lblOne.text = empData.fname
cell.lblTwo.text = empData.emp_desig
cell.lblThree.text = empData.emp_exp
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
Can someone help me with this error I have no idea what does this error mean I have seen the same type error most of the places and tried to solve it but still the same error from the server
my postman
]4
I got the same error and I searched a lot by changing contentType and many more things but none is fixed it. PostMan Raw and Preview Tab response gives me idea where the exact issue.
Raw
Preview
This error occur because of Connected to MySQL text beginning of response. so inform your developer about this, he will solve this and may be the error solve.

I can't seem to access sub arrays in swiftyJSON

So here is the JSON
{
"city": {
"id": 4930956,
"name": "Boston",
"coord": {
"lon": -71.059769,
"lat": 42.358429
},
"country": "US",
"population": 0,
"sys": {
"population": 0
}
},
"cod": "200",
"message": 0.0424,
"cnt": 39,
"list": [
{
"dt": 1473476400,
"main": {
"temp": 76.33,
"temp_min": 73.11,
"temp_max": 76.33,
"pressure": 1026.47,
"sea_level": 1027.96,
"grnd_level": 1026.47,
"humidity": 73,
"temp_kf": 1.79
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
"clouds": {
"all": 8
},
"wind": {
"speed": 7.29,
"deg": 300.501
},
Here is my Controller where I go grab the data......
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var amConnected: UILabel!
#IBOutlet weak var weatherTable: UITableView!
var arrRes = [[String:AnyObject]]()
var swiftyJsonVar: JSON?
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.doSomethingNotification(_:)), name: "ReachabilityChangedNotification", object: nil)
let openWMAPI = "http://api.openweathermap.org/data/2.5/forecast/city?q=Boston,Ma&APPID=XXXXXXXXXXXXXXX&units=imperial"
Alamofire.request(.GET,openWMAPI).responseJSON{
(responseData) -> Void in
print(responseData)
let swiftyJsonVar = JSON(responseData.result.value!)
self.weatherTable.reloadData()
}
.responseString{ response in
//print(response.data.value)
// print(response.result.value)
//print(response.result.error)
//eprint("inhere");
}
weatherTable.rowHeight = UITableViewAutomaticDimension
weatherTable.estimatedRowHeight = 140
// Do any additional setup after loading the view, typically from a nib.
}
In my table loop it is now saying that the jsonArray is nil and failing.
I'm unsure as to what I'm doing wrong at this point.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = weatherTable.dequeueReusableCellWithIdentifier("theCell", forIndexPath: indexPath)
let label1 = cell.viewWithTag(101) as! UILabel
print("inhere")
if((swiftyJsonVar) != nil){
if let jsonArray = self.swiftyJsonVar["list"].array {
var temp = jsonArray[indexPath.row]["main"]["temp"].float
var rdate = jsonArray[indexPath.row]["dt_txt"].string
print(temp)
}else{
print("test")
}
}
label1.text = "TEST"
return cell
}
OVerall I'm just not sure how to dig down into the next level of the JSON.
If you are not averse to it, try using AlamofireObjectMapper instead of SwiftyJson
1) If you are going to change the name of the json keys very often, and are going to do a lot of enum transformations try :
AlamofireObjectMapper
2) If the names are going to be the same, with minimal transformations, directly use :
AlamofireJsonToObjects
Both of these cases, create model classes for your json object. If you have an array - you can define a var as an array
if it is an object or an array of objects - you can then create another model class which is again Mappable and then define such an object var in the original model.
The above libraries will make your code extremely clean while extracting objects to json.
You can access to the elements inside an JSON array in SwiftyJSON using consecutive subscripts, if we have the following JSON for example:
var json: JSON = ["name": "Jack", "age": 25,
"list": ["a", "b", "c", ["what": "this"]]]
Then you can access to the four element of the subarray listcontained in the main array in the following way for example:
json["list"][3]["what"] // this
Or you can define a path like this let path = ["list",3,"what"] and then call it in this way:
json[path] // this
With the above explained let's introduce it with your JSON file to list the elements inside the array weather:
if let jsonArray = json["list"].array {
// get the weather array
if let weatherArray = jsonArray[0]["weather"].array {
// iterate over the elements of the weather array
for index in 0..<weatherArray.count {
// and then access to the elements inside the weather array using optional getters.
if let id = weatherArray[index]["id"].int, let main = weatherArray[index]["main"].string {
print("Id: \(id)")
print("Main: \(main)")
}
}
}
}
And you should see in the console:
Id: 800
Main: Clear
I hope this help you.

How I can read nested array at JSON file by SWIFT 2

I wrote this code to read country at table view from this JSON file :
JSON:
[5]
0: {
"country": "Afghanistan"
"code": "AF"
}-
1: {
"country": "Ă…land Islands"
"code": "AX"
}-
2: {
"country": "Albania"
"code": "AL"
}-
3: {
"country": "Algeria"
"code": "DZ"
}-
4: {
"country": "American Samoa"
"code": "AS"
}
My code :
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate {
#IBOutlet weak var tableCountryView: UITableView!
var json_url = "........ my url here ......... "
var TableData:Array< datastruct > = Array < datastruct >()
enum ErrorHandler:ErrorType
{
case ErrorFetchingResults
}
struct datastruct
{
var country_name:String?
var country_code:String?
init(add: NSDictionary)
{
country_name = add["country"] as? String
country_code = add["code"] as? String
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableCountryView.dataSource = self
tableCountryView.delegate = self
get_data_from_url(json_url)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let data = TableData[indexPath.row]
cell.textLabel?.text = data.country_name! + " - " + data.country_code!
return cell
}
func get_data_from_url(url:String)
{
let url:NSURL = NSURL(string: url)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
dispatch_async(dispatch_get_main_queue(), {
self.extract_json(data!)
return
})
}
task.resume()
}
func extract_json(jsonData:NSData)
{
let json: AnyObject?
do {
json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
} catch {
json = nil
return
}
if let list = json as? NSArray
{
for (var i = 0; i < list.count ; i++ )
{
if let data_block = list[i] as? NSDictionary
{
TableData.append(datastruct(add: data_block))
}
}
do_table_refresh()
}
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableCountryView.reloadData()
return
})
}
}
This code is working true for the first JSON syntax but if I want to read sub-array like the syntax at the following JSON file , how I can edit that in my previous code.
JSON:
{
"Countries": [4]
0: {
"countryname": "Egypt"
"code": "20"
}-
1: {
"countryname": "India"
"code": "91"
}-
2: {
"countryname": "United States"
"code": "1"
}-
3: {
"countryname": "Turkey"
"code": "90"
}-
}
Also I have the button at my storyboard and I want to show this table view of country when clicking on this button and then choose one country and close this table and show the result on the button , I know this easy but I started to learn IOS from 2 weeks only, I hope if you can give me advice in these cases.

Resources