Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get data from Json and put it in the table and display it from the API via Alamofire through the 'Post' process that has parameters containing the page number
I want get "results" ..
{
"responseCode": 200,
"message": null,
"status": true,
"results": [
{
"id": 971,
"title": "ST201972362",
"cdate": "07/31/2019",
"summary": "test",
"address": "",
"timer": "77876203",
"lat": "31.515934",
"lng": "34.4494066",
"source": "2",
"CreatedOn": "2019-07-31T13:38:46.927",
"done_940": null
},
{
"id": 970,
"title": "ST201972356",
"cdate": "07/30/2019",
"summary": "ov",
"address": "",
"timer": "0",
"lat": "31.5159315",
"lng": "34.4493925",
"source": "2",
"CreatedOn": "2019-07-30T15:26:00.077",
"done_940": null
},
{
"id": 964,
"title": "ST201972341",
"cdate": "07/29/2019",
"summary": "تجربة بلاغ ",
"address": "",
"timer": "0",
"lat": "21.5066086",
"lng": "39.1758587",
"source": "2",
"CreatedOn": "2019-07-29T19:06:58.817",
"done_940": null
},
{
"id": 959,
"title": "ST201972820252314",
"cdate": "07/28/2019",
"summary": "اااااا",
"address": "",
"timer": "0",
"lat": "21.5066716",
"lng": "39.1758483",
"source": "1",
"CreatedOn": "2019-07-28T11:45:02.493",
"done_940": null
},
{
"id": 957,
"title": "ST201972312",
"cdate": "07/28/2019",
"summary": "تمتمتم",
"address": "",
"timer": "0",
"lat": "31.5397884",
"lng": "34.4544891",
"source": "2",
"CreatedOn": "2019-07-28T08:56:43.577",
"done_940": null
},
{
"id": 956,
"title": "ST201972312",
"cdate": "07/28/2019",
"summary": "لا تنام",
"address": "",
"timer": "0",
"lat": "31.5397238",
"lng": "34.4540829",
"source": "2",
"CreatedOn": "2019-07-28T08:56:00.15",
"done_940": null
},
{
"id": 955,
"title": "ST201972311",
"cdate": "07/28/2019",
"summary": "تجربه جديد",
"address": "",
"timer": "0",
"lat": "31.5395001",
"lng": "34.4542211",
"source": "2",
"CreatedOn": "2019-07-28T08:52:09.81",
"done_940": null
},
{
"id": 953,
"title": "ST201972309",
"cdate": "07/28/2019",
"summary": "يلا",
"address": "",
"timer": "0",
"lat": "31.5110196",
"lng": "34.4784933",
"source": "2",
"CreatedOn": "2019-07-28T05:30:29.647",
"done_940": null
},
{
"id": 952,
"title": "ST201972309",
"cdate": "07/28/2019",
"summary": "ماك ١",
"address": "",
"timer": "0",
"lat": "31.5110291",
"lng": "34.4785841",
"source": "2",
"CreatedOn": "2019-07-28T05:29:09.943",
"done_940": null
},
{
"id": 949,
"title": "ST201972307",
"cdate": "07/28/2019",
"summary": "مرحبا",
"address": "",
"timer": "0",
"lat": "31.5443154",
"lng": "34.4585304",
"source": "2",
"CreatedOn": "2019-07-28T00:20:42.753",
"done_940": null
}
],
"done_940": "2/811"
}
You can follow some steps:
Step 1: need to create model
struct ResultObject {
var responseCode: Int?
var message: String?
var status: Bool?
var result: [Result]
public init(response: [String: Any]) {
self.responseCode = response["responseCode"] as? Int
self.message = response["message"] as? String
self.status = response["status"] as? Bool
let results = response["result"] as! [[String: Any]]
self.result = []
for item in results {
let result = Result(result: item)
self.result.append(result)
}
}
struct Result {
var id: String?
var title: String?
var cdate: String?
var summary: String?
var address: String?
var timer: String?
var lat: String?
var lng: String?
var source: String?
var CreatedOn: String?
var done_940: String?
public init(result: [String: Any]) {
self.id = result["id"] as? String
self.title = result["title"] as? String
self.cdate = result["cdate"] as? String
self.summary = result["summary"] as? String
self.address = result["address"] as? String
self.timer = result["timer"] as? String
self.lat = result["lat"] as? String
self.lng = result["lng"] as? String
self.source = result["source"] as? String
self.CreatedOn = result["CreatedOn"] as? String
self.done_940 = result["done_940"] as? String
}
}
}
Step 2: You check response from Alamofile
if you get json then
let test = ResultObject(response: responseJson)
print(test)
incase you get response is type Response you must convert into json
let responseJSON = try? JSONSerialization.jsonObject(with: response.data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
let test = ResultObject(response: responseJSON)
print(test)
}
Let me know when you have some other problems.
To parse a JSON, as I found also on the web, I usually used this kind of code:
guard let results = receivedUserJSON["results"] as? [String: Any] else {
print("Error interpreting results")
return
}
This time I have a problem, because it seems to end in the else of this guard let. The JSON has the following structure:
{
"results": [{
"gender": "female",
"name": {
"title": "mrs",
"first": "silene",
"last": "almeida"
},
"location": {
"street": "2594 rua maranhão ",
"city": "pouso alegre",
"state": "distrito federal",
"postcode": 20447,
"coordinates": {
"latitude": "-70.0198",
"longitude": "123.6577"
},
"timezone": {
"offset": "+4:30",
"description": "Kabul"
}
},
"email": "silene.almeida#example.com",
"login": {
"uuid": "d06a46b3-1c00-42be-b8fc-d271bf901f7d",
"username": "silversnake251",
"password": "ventura",
"salt": "UcckU6RG",
"md5": "7c8c4129587c61da01ca7cf4f88353c5",
"sha1": "6cbf7ec377ff4ebad5a392ec487343bf613858ef",
"sha256": "8dedf3649fb833a1936b8885627b86c6cf02062eb74f727b2cbd674a30f73e75"
},
"dob": {
"date": "1969-07-13T00:58:26Z",
"age": 49
},
"registered": {
"date": "2003-09-28T09:44:56Z",
"age": 15
},
"phone": "(95) 0094-8716",
"cell": "(20) 1014-3529",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/women/66.jpg",
"medium": "https://randomuser.me/api/portraits/med/women/66.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/women/66.jpg"
},
"nat": "BR"
}],
"info": {
"seed": "dd971cddf636d2d7",
"results": 1,
"page": 1,
"version": "1.2"
}
}
What should I do to properly parse this JSON? I would prefer not to go for the Codable solution because I don't need all of these values.
PS: I know the json is correct because I tried and printed it with:
if let JSONString = String(data: responseData, encoding: String.Encoding.utf8) {
print(JSONString)
}
results is an array
guard let results = receivedUserJSON["results"] as? [[String:Any]] else {
print("Error interpreting results")
return
}
I see no value for it to be an array as it contains 1 element so you may think to alter this json
current strucsture
{
"results": [{}],
"info": {
"seed": "dd971cddf636d2d7",
"results": 1,
"page": 1,
"version": "1.2"
}
}
you may alter it to
{
"results": {},
"info": {
"seed": "dd971cddf636d2d7",
"results": 1,
"page": 1,
"version": "1.2"
}
}
Below is the code i tried to extract the JSON Object. I only want the Data with the status != Static and show that in tableView
postman response
[
{
"id": 249,
"name": "aBrush your teeth",
"desc": "Brush your teeth",
"reward": "1.00",
"sched": "2015-01-01T08:00:00+08:00",
"parent": "",
"type": "",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "static"
},
"date_created": "2018-04-25T14:27:20.405928+08:00",
"date_modified": "2018-04-26T11:56:02.030647+08:00"
},
{
"id": 250,
"name": "Brush your teeth",
"desc": "Brush your teeth",
"reward": "1.00",
"sched": "2015-01-01T08:00:00+08:00",
"parent": "",
"type": "",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "static"
},
"date_created": "2018-04-25T14:28:49.780354+08:00",
"date_modified": "2018-04-26T11:56:05.616333+08:00"
},
{
"id": 252,
"name": "Brush your teeth",
"desc": "Brush your teeth",
"reward": "1.00",
"sched": "2015-01-01T08:00:00+08:00",
"parent": "",
"type": "",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "static"
},
"date_created": "2018-04-25T14:31:02.274405+08:00",
"date_modified": "2018-04-26T11:59:57.676148+08:00"
},
{
"id": 253,
"name": "Brush your teeth",
"desc": "Brush your teeth",
"reward": "1.00",
"sched": "2015-01-01T08:00:00+08:00",
"parent": "",
"type": "",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "static"
},
"date_created": "2018-04-25T14:34:37.097498+08:00",
"date_modified": "2018-04-26T09:42:24.633359+08:00"
},
{
"id": 254,
"name": "Brush your teeth",
"desc": "Brush your teeths",
"reward": "1.00",
"sched": "2015-01-01T08:00:00+08:00",
"parent": "",
"type": "",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "static"
},
"date_created": "2018-04-25T14:36:53.766088+08:00",
"date_modified": "2018-04-26T11:56:15.757769+08:00"
},
{
"id": 260,
"name": "chorename",
"desc": "{\n \"questions\" : [\n {\n \"b\" : 2,\n \"a\" : 1\n },\n {\n \"b\" : 3,\n \"a\" : 2\n },\n {\n \"b\" : 2,\n \"a\" : 8\n },\n {\n \"b\" : 9,\n \"a\" : 7\n },\n {\n \"b\" : 3,\n \"a\" : 6\n }\n ],\n \"operation\" : \"+\"\n}",
"reward": "1.00",
"sched": "2018-04-19T15:54:24.657644+08:00",
"parent": "shit",
"type": "homework",
"child": "",
"occurrence": {
"name": "once"
},
"status": {
"name": "ongoing"
},
"date_created": "2018-04-26T10:13:42.913149+08:00",
"date_modified": "2018-04-26T10:13:42.953485+08:00"
}
]
code in getting the data
// here i only want to get data from the dapi which status name != "static"
and append it to getalldetail which is an var getAllDetail: [[String:Any]] = [String:Any]
func demoApi() {
Alamofire.request("test.api", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else{ return}
print("Api Response : \(json)")
// here i only want to get data from the dapi which status name != "static"
for item in json {
self.getAllDetail.append(item)
}
if !self.getAllDetail.isEmpty{
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
break
case .failure(_):
print("Error")
break
}
}
}
Just apply filter to your response as like below.
let filtered = json.filter { (dict) -> Bool in
guard let status : [String : String] = dict["status"] as? [String : String], let statusString = status["name"] else {
return false
}
return statusString.compare("static") != .orderedSame
}
I recommend to take advantage of the Codable protocol of Swift 4 and decode the JSON into structs. This makes it very easy to filter the data. No type cast needed, no key subscription needed.
Create the structs
struct ResponseData : Decodable {
let id: Int
let name, desc, reward : String
let sched, parent, type, child : String
let occurrence : Status
let status : Status
let dateCreated, dateModified : String
}
struct Status : Decodable {
let name : String
}
Your data source array getAllDetail must be declared as
var getAllDetail = [ResponseData]()
In the Alamofire completion handler get the data and decode the JSON into the structs with JSONDecoder. The items can be filtered – pretty descriptively – with filter{ $0.status.name == "static" }
Alamofire.request("test.api", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
switch(response.result) {
case .success:
guard let data = response.data else { return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try decoder.decode([ResponseData].self, from: data)
self.getAllDetail = result.filter{ $0.status.name == "static" }
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failure(let error):
print("Error", error)
}
}
I am having a JSON array which looks like this:
func fetchProfessionalData() {
guard let url = URL(string:"urlString") else { return }
let parameters = ["Address":""] as [String : Any]
Alamofire.request(url, method: .post, parameters:parameters,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
let jsonData = response.result.value as! NSArray
print("response:\(jsonData)")
}
self.listTableView.reloadData()
break
case .failure(let error):
print(error)
}
}
}
this is the output I'm getting when I print it:
response: [
{
"userId": 2,
"userName": "jhonsmith",
"password": "1234",
"userTypeId": 3,
"firstName": "jhon",
"lastName": "smith",
"dob": "0004-03-04T00:00:00",
"phoneNumber": "40556677",
"mobile": "324",
"email": "jhon",
"profilePic": "avatar3.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "2 years",
"about": "I am expertised in beauty care",
"addressId": 2,
"addressLine1": "7 Freymuth Rd",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 3,
"serviceName": "BeautyCare",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 5,
"subServiceName": "HairCare",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 500,
"serviceProviderId": 2,
"providerServiceId": 1
},
{
"serviceId": 4,
"serviceName": "Carpentry",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 6,
"subServiceName": "All Carpentry",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 400,
"serviceProviderId": 2,
"providerServiceId": 1002
}
],
"rating": 3,
"price": 0,
"searchLocationId": 0
},
{
"userId": 4,
"userName": "User",
"password": "new",
"userTypeId": 3,
"firstName": "Emma",
"lastName": "Williams",
"dob": "1998-06-23T00:00:00",
"phoneNumber": "7787787887",
"mobile": "9879789990",
"email": "user#testmail.com",
"profilePic": "avatar4.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "2 years",
"about": "Test",
"addressId": 4,
"addressLine1": "Big river dr",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 1,
"serviceName": "Cleaning",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 1,
"subServiceName": "Dusting",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 2,
"serviceProviderId": 4,
"providerServiceId": 3
}
],
"rating": 0,
"price": 0,
"searchLocationId": 0
},
{
"userId": 5,
"userName": "RobertThomas",
"password": "rb",
"userTypeId": 3,
"firstName": "Robert",
"lastName": "Thomas",
"dob": "1999-01-04T00:00:00",
"phoneNumber": "889955643",
"mobile": "1234567890",
"email": "rb1234#testmail.com",
"profilePic": "th.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "1 Year",
"about": "Robert Thomas",
"addressId": 5,
"addressLine1": "Little Piney Dr",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 2,
"serviceName": "ChildCare",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 3,
"subServiceName": "Baby Sitting",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 7,
"serviceProviderId": 5,
"providerServiceId": 4
}
],
"rating": 0,
"price": 0,
"searchLocationId": 0
}
]
Now I am having a tableViewCell where I have to show "userName", "profilePic","rating","email" and "serviceName" under "lstServiceProviders".So far I am able to show name,image,email,rating but "lstServiceProviders" is another array of dictionaries. I want to show all the services provided by that serviceProvider in cell.
lets say in json 1st dict the "userName":"jhonsmith" is having "lstServicePrpviders" with an array of two dictionaries with "serviceName": "BeautyCare" in 1st Dict and "serviceName":"Carpentry" in 2nd Dict. I want to show both BeautyCare and Carpentry in one cell. how to do this.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let listCell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) as! ListTableViewCell
let string = "imageBaseUrl\(models![indexPath.row].profilePic!)"
let escapedAddress = string.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlQueryAllowed)
listCell.listCellImage.image = UIImage(url: URL(string: escapedAddress!))
listCell.listCellNamesLabel.text = models![indexPath.row].userName!
let rating = models![indexPath.row].rating!
listCell.listCellRating.text = "(\(rating)/5 & 5 Comments)"
listCell.listCellStarRating.text = ratingArray[indexPath.row]
for i in 0..< models![indexPath.row].lstServiceProviders!.count {
listCell.listCellServicesLbl.text =
models![indexPath.row].lstServiceProviders[i].serviceName
}
return listCell
}
[Swift 4] You can use models with Codable to easily manage your tableviewcell.
See the Code below and run in a playground, you will understand that i have created model objects which is easy to loop and manage:
var json = """
[
{
"userId": 2,
"userName": "jhonsmith",
"password": "1234",
"userTypeId": 3,
"firstName": "jhon",
"lastName": "smith",
"dob": "0004-03-04T00:00:00",
"phoneNumber": "40556677",
"mobile": "324",
"email": "jhon",
"profilePic": "avatar3.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "2 years",
"about": "I am expertised in beauty care",
"addressId": 2,
"addressLine1": "7 Freymuth Rd",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 3,
"serviceName": "BeautyCare",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 5,
"subServiceName": "HairCare",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 500,
"serviceProviderId": 2,
"providerServiceId": 1
},
{
"serviceId": 4,
"serviceName": "Carpentry",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 6,
"subServiceName": "All Carpentry",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 400,
"serviceProviderId": 2,
"providerServiceId": 1002
}
],
"rating": 3,
"price": 0,
"searchLocationId": 0
},
{
"userId": 4,
"userName": "User",
"password": "new",
"userTypeId": 3,
"firstName": "Emma",
"lastName": "Williams",
"dob": "1998-06-23T00:00:00",
"phoneNumber": "7787787887",
"mobile": "9879789990",
"email": "user#testmail.com",
"profilePic": "avatar4.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "2 years",
"about": "Test",
"addressId": 4,
"addressLine1": "Big river dr",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 1,
"serviceName": "Cleaning",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 1,
"subServiceName": "Dusting",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 2,
"serviceProviderId": 4,
"providerServiceId": 3
}
],
"rating": 0,
"price": 0,
"searchLocationId": 0
},
{
"userId": 5,
"userName": "RobertThomas",
"password": "rb",
"userTypeId": 3,
"firstName": "Robert",
"lastName": "Thomas",
"dob": "1999-01-04T00:00:00",
"phoneNumber": "889955643",
"mobile": "1234567890",
"email": "rb1234#testmail.com",
"profilePic": "th.jpg",
"profileImage": null,
"isDeleted": false,
"company": "",
"experience": "1 Year",
"about": "Robert Thomas",
"addressId": 5,
"addressLine1": "Little Piney Dr",
"addressLine2": "",
"city": "St.Louis",
"state": "MO",
"country": "USA",
"zipCode": "63367",
"serviceProviderId": 0,
"serviceId": 0,
"subServiceId": 0,
"relevantExp": null,
"costPerHour": 0,
"spbRow": null,
"lstServiceProviders": [
{
"serviceId": 2,
"serviceName": "ChildCare",
"serviceDescription": null,
"serviceLogo": null,
"serviceIsDeleted": false,
"serviceIdFK": 0,
"subServiceId": 3,
"subServiceName": "Baby Sitting",
"subServiceDescription": null,
"subServiceLogo": null,
"subServiceIsDeleted": false,
"costPerHour": 7,
"serviceProviderId": 5,
"providerServiceId": 4
}
],
"rating": 0,
"price": 0,
"searchLocationId": 0
}
]
""".data(using: .utf8)
struct LstServiceProviders : Codable {
let serviceId : Int?
let serviceName : String?
let serviceDescription : String?
let serviceLogo : String?
let serviceIsDeleted : Bool?
let serviceIdFK : Int?
let subServiceId : Int?
let subServiceName : String?
let subServiceDescription : String?
let subServiceLogo : String?
let subServiceIsDeleted : Bool?
let costPerHour : Int?
let serviceProviderId : Int?
let providerServiceId : Int?
enum CodingKeys: String, CodingKey {
case serviceId = "serviceId"
case serviceName = "serviceName"
case serviceDescription = "serviceDescription"
case serviceLogo = "serviceLogo"
case serviceIsDeleted = "serviceIsDeleted"
case serviceIdFK = "serviceIdFK"
case subServiceId = "subServiceId"
case subServiceName = "subServiceName"
case subServiceDescription = "subServiceDescription"
case subServiceLogo = "subServiceLogo"
case subServiceIsDeleted = "subServiceIsDeleted"
case costPerHour = "costPerHour"
case serviceProviderId = "serviceProviderId"
case providerServiceId = "providerServiceId"
}
}
struct RootModel : Codable {
let userId : Int?
let userName : String?
let password : String?
let userTypeId : Int?
let firstName : String?
let lastName : String?
let dob : String?
let phoneNumber : String?
let mobile : String?
let email : String?
let profilePic : String?
let profileImage : String?
let isDeleted : Bool?
let company : String?
let experience : String?
let about : String?
let addressId : Int?
let addressLine1 : String?
let addressLine2 : String?
let city : String?
let state : String?
let country : String?
let zipCode : String?
let serviceProviderId : Int?
let serviceId : Int?
let subServiceId : Int?
let relevantExp : String?
let costPerHour : Int?
let spbRow : String?
let lstServiceProviders : [LstServiceProviders]?
let rating : Int?
let price : Int?
let searchLocationId : Int?
enum CodingKeys: String, CodingKey {
case userId = "userId"
case userName = "userName"
case password = "password"
case userTypeId = "userTypeId"
case firstName = "firstName"
case lastName = "lastName"
case dob = "dob"
case phoneNumber = "phoneNumber"
case mobile = "mobile"
case email = "email"
case profilePic = "profilePic"
case profileImage = "profileImage"
case isDeleted = "isDeleted"
case company = "company"
case experience = "experience"
case about = "about"
case addressId = "addressId"
case addressLine1 = "addressLine1"
case addressLine2 = "addressLine2"
case city = "city"
case state = "state"
case country = "country"
case zipCode = "zipCode"
case serviceProviderId = "serviceProviderId"
case serviceId = "serviceId"
case subServiceId = "subServiceId"
case relevantExp = "relevantExp"
case costPerHour = "costPerHour"
case spbRow = "spbRow"
case lstServiceProviders = "lstServiceProviders"
case rating = "rating"
case price = "price"
case searchLocationId = "searchLocationId"
}
}
let Models = try! JSONDecoder().decode([RootModel].self, from: json!)
print(Models.count)
for item in Models {
print(item.lstServiceProviders?.count)
}
[Edit 1] If the response is Data, use the below:
URLSession.shared.dataTask(with: gitUrl) { (data, response
, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let models = try decoder.decode([RootModel].self, from: data)
} catch let err {
print("Err", err)
}
}.resume()
If the response is Json object like your output, use the below:
func fetchProfessionalData() {
guard let url = URL(string:"urlString") else { return }
let parameters = ["Address":""] as [String : Any]
Alamofire.request(url, method: .post, parameters:parameters,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
// let jsonData = response.result.value as! NSArray
let jsonData = try JSONSerialization.data(withJSONObject: response.result, options: .prettyPrinted)
models = try JSONDecoder().decode([RootModel].self, from: jsonData)
print("response:\(jsonData)")
}
// self.listTableView.reloadData()
break
case .failure(let error):
print(error)
}
}
}
In your viewController, Declare varibale
var models: [RootModel]? {
didSet {
self.listTableView.reloadData()
}
}
In your tableview delegate method
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Update your cell using models
// cell.text = models[indexPath.row].userName
}
[Edit 2] Add all string and then show the value.
var stringArray:[String] = []
for i in 0..< models![indexPath.row].lstServiceProviders!.count {
stringArray.append( models![indexPath.row].lstServiceProviders[i].serviceName)
}
listCell.listCellServicesLbl.text = stringArray.joined(separator: ", ")
{
"firstName": "AA",
"lastName": "BB,
"shortName": "CC",
"nric": "12/AAA(N)123456",
"gender": "F",
"dob": "1.1.2000",
"password": "admin123",
"photo": {
"image": "hello",
"thumb": "world"
}
}
Is there anyway how to add photo array in main array? I've done as follow
let photoArray = [
"image": imageBase64,
"thumb": imageBase64
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
but output is awful. Please let me how to do it.
Instead of making the param let make it var and do the following. You do need to specify the dictionary type as below
let photoArray : [String : AnyObject] = [
"pic" : "myPhoto"
]
var param : [String : AnyObject] = [
"name" : "UserName"
]
param["photo"] = photoArray
let photoArray = [[
"image": "a",
"thumb": "b"],[
"image": "a",
"thumb": "b"]
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
Hope you want like this.
let photoArray:[String:UIImage] = [
"image": UIImage.init(named: "a.png")!,
"thumb": UIImage.init(named: "b.png")!
]
let param:[String:AnyObject] = [
"firstName": "AA",
"lastName": "BB",
"shortName": "CC",
"nric": "",
"gender": 0,
"dob": "DD",
"photo": photoArray
]
You can do it like this