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 6 years ago.
Improve this question
{
"status": "true",
"message": "11 records found",
"response": [
{
"name": "1",
"address": "565400-",
"phone": "",
"gym_email": "",
"images": ""
},
{
"name": "123",
"address": "102-",
"phone": "",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "",
"gym_email": "1#2.com",
"images": "a:1:{i:0;s:18:\"1478177269200.jpeg\";}"
},
{
"name": "Burn Gym",
"address": "NAC,ManimajraChandigarhPanchkula-134112",
"phone": "",
"gym_email": null,
"images": ""
},
{
"name": "Burn Gym & Spa",
"address": "Sector 11,ChandigarhAmbala-160101",
"phone": "585888",
"gym_email": "1#2.com",
"images": ""
},
{
"name": "test gym",
"address": "Sector 11,HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "1#2.com",
"images": "a:1:{i:1;s:17:\"1478579644341.png\";}"
},
{
"name": "test gym",
"address": "Sector 12HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "new gym",
"address": "sector 11HaryanaPanchkula-134112",
"phone": "789654123",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 4HaryanaPanchkula-134101",
"phone": "0",
"gym_email": "",
"images": ""
},
{
"name": "hrhrrth",
"address": "sector 11HaryanaPanchkula-134101",
"phone": "8054233444",
"gym_email": "keshavkpnf#gmail.com",
"images": ""
}
]
}
You can get the value of address as:
guard let response = json["response"] as? [[String:AnyObject]] else {
print("Nothing here")
return
}
then you can get address from the response array by looping,
for data in response {
print(data["address"] as? String)
}
if((jsonResult) != nil) {
let swiftyJsonVar = jsonResult!
do {
if let dicObj = swiftyJsonVar as? NSDictionary {
print("Response is dictionary")
print(dicObj)
let arrObj = dicObj["response"] as NSArray
// Then iterate your arrObj and do as per your need.
//for eg.
arrObj[0]["address"]
}
}
}
addressLabel.text=[[[mdict objectForKey:#"response"]objectAtIndex:indexPath.row]valueForKey:#"address"];
Related
I am trying to create a table view with a collection view in each cell. My JSON structure is like Main Menu title for the tv cell and in each main object, I receive a submenu, whose data I want to use in the collection view.
The issue I am facing is in using indexes of table cell and collection cell to get the nested data. Here is my JSON
"MainMenu": [
{
"ID": 8,
"MasterID": 12,
"Title": "Payment",
"Image": "image.png",
"SubMenu": [
{
"ID": 9,
"Title": "My Bill",
"Image": "image.png"
},
{
"ID": 10,
"Title": "Electricity ",
"Image": "image.png"
},
{
"ID": 11,
"Title": "Gas",
"Image": "image.png"
},
{
"ID": 12,
"Title": "Telephone",
"Image": "image.png"
},
{
"ID": 13,
"Title": "Water",
"Image": "image.png"
}
]
},
{
"ID": 40,
"MasterID": 14,
"Title": "Services",
"Image": "image.png",
"SubMenu": [
{
"ID": 32,
"Title": "Upload Slip",
"Image": "image.png"
},
{
"ID": 41,
"Title": "SRY (Self Reliant Youth)",
"Image": "image.png"
},
{
"ID": 42,
"Title": "Dollor Product Purchase ",
"Image": "image.png"
},
{
"ID": 43,
"Title": "ARY Coin Redemption",
"Image": "image.png"
},
{
"ID": 44,
"Title": "Pay Via QR",
"Image": "image.png"
},
{
"ID": 45,
"Title": "Card Request",
"Image": "image.png"
}
]
},
{
"ID": 14,
"MasterID": 8,
"Title": "Mobile Balance",
"Image": "image.png",
"SubMenu": [
{
"ID": 15,
"Title": "My Mobile",
"Image": "image.png"
},
{
"ID": 16,
"Title": "Mobilink",
"Image": "image.png"
},
{
"ID": 17,
"Title": "Telenor",
"Image": "image.png"
},
{
"ID": 18,
"Title": "Ufone",
"Image": "image.png"
},
{
"ID": 19,
"Title": "Warid",
"Image": "image.png"
},
{
"ID": 20,
"Title": "Zong",
"Image": "image.png"
}
]
},
{
"ID": 46,
"MasterID": 6,
"Title": "Help",
"Image": "image.png",
"SubMenu": [
{
"ID": 47,
"Title": "Call",
"Image": "image.png"
},
{
"ID": 48,
"Title": "Chat",
"Image": "image.png"
},
{
"ID": 49,
"Title": "Email",
"Image": "image.png"
},
{
"ID": 50,
"Title": "Others",
"Image": "image.png"
},
{
"ID": 51,
"Title": "VAS / SMS",
"Image": "image.png"
}
]
},
{
"ID": 21,
"MasterID": 5,
"Title": "Fund Transfer",
"Image": "image.png",
"SubMenu": [
{
"ID": 22,
"Title": "To Other ARY Wallet",
"Image": "image.png"
},
{
"ID": 23,
"Title": "To Bank Account",
"Image": "image.png"
}
]
},
{
"ID": 34,
"MasterID": 1,
"Title": "$ & MilliGold Deal",
"Image": "image.png",
"SubMenu": [
{
"ID": 35,
"Title": "$ Deposit",
"Image": "image.png"
},
{
"ID": 36,
"Title": "$ Purchase",
"Image": "image.png"
},
{
"ID": 37,
"Title": "$ Time Games",
"Image": "image.png"
},
{
"ID": 38,
"Title": "Scan for Bid",
"Image": "image.png"
}
]
}
],
"CustomerAccountInformation": []
}
Please guide me how can I use my JSON objects each in different tablecell.
Here is what I have tried:
TVCell
cell.titleLabel.text = menu?.mainMenu?[indexPath.row].title ?? "Our services"
CollectionCell
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[indexPath.row].subMenu?[indexPath.row].image)!)!)
First, in your tableview cell, set the tag of the collectionview to indexPath.row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : TVCell = tableview.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell
cell.myCollectionView.tag = indexPath.row
return cell
}
Now in your collectionview cell you can parse the data like following
let index = cell.tag
cell.image.af_setImage(withURL: URL.init(string: (menu?.mainMenu?[index].subMenu?[indexPath.row].image)!)!)
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.
I am trying to read from a local JSON file and populate my tableView with cells to be retrieved from the Decoder. Since my table view was still empty, I added a breakpoint on the JSONDecoder.decode line to see what is going on. I get this error, even though I made sure that my naming convention is the same in both my structs and JSON file. Is there something I am missing here.
Since my naming convention was consistent across the files, at first I did not try add CodingKeys enum inside my structs. After a few failed runs I added that in but it feels kind of obsolete.
Where I run the decoder:
let fileName = "settings"
...
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let list = try JSONDecoder().decode(SettingsPayload.self, from: data)
completion(list.sections)
} catch {
completion(nil)
}
}
fileprivate struct SettingsPayload: Decodable {
let sections: [Section]
}
My structs that will be used to store the data when retrieved:
struct Item: Decodable {
let title: String
let type: String
let url: String
private enum CodingKeys: String, CodingKey {
case title = "title"
case type = "type"
case url = "url"
}
}
struct Section: Decodable {
let title: String
let items: [Item]
private enum CodingKeys: String, CodingKey {
case title = "title"
case items = "items"
}
}
and my .json file:
{
"sections": [{
"section": {
"title": "Main Settings",
"items": [{
"item": {
"title": "Notifications",
"type": "notification",
"url": ""
},
"item": {
"title": "Log Out",
"type": "",
"url": ""
}
}]
},
"section": {
"title": "Feedback",
"items": [{
"item": {
"title": "Contact Us",
"type": "email",
"url": ""
},
"item": {
"title": "Rate on App Store",
"type": "webView",
"url": "https://www.apple.com/uk/ios/app-store/"
}
}]
},
"section": {
"title": "About",
"items": [{
"item": {
"title": "Terms of Service",
"type": "webView",
"url": ""
},
"item": {
"title": "Privacy Policy",
"type": "webView",
"url": "https://www.apple.com/uk/ios/app-store/"
},
"item": {
"title": "Version Info",
"type": "webView",
"url": ""
}
}]
}
}]
}
This is the error message I get:
- debugDescription : "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\")."
I think the problem is that the decoder expects an Array of the item Section, but your json has an Array of dictionaries with a key "section" and an item Section in there.
Maybe try to modify your json like this:
{
"sections": [{
"title": "Main Settings",
"items": [ {
"title": "Notifications",
"type": "notification",
"url": ""
}, {
"title": "Log Out",
"type": "",
"url": ""
}]}, {
"title": "Feedback",
"items": [{
"title": "Contact Us",
"type": "email",
"url": ""
},{
"title": "Rate on App Store",
"type": "webView",
"url": "https://www.apple.com/uk/ios/app-store/"
}]}, {
"title": "About",
"items": [{
"title": "Terms of Service",
"type": "webView",
"url": ""
}, {
"title": "Privacy Policy",
"type": "webView",
"url": "https://www.apple.com/uk/ios/app-store/"
}, {
"title": "Version Info",
"type": "webView",
"url": ""
}
]}]
}
Update
JSONDecoder doesn't look for the name of your decodable struct in the JSON, it only looks for the name of the properties.
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"
}
}
My Code:
var nameArray = [String]()
do
{
let arrayValues = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(arrayValues.count)
print(arrayValues)
let limit = arrayValues.count-1
for i in 0...limit
{
let x = i
let dataValues = arrayValues.object(forKey: "result" ) as! NSDictionary // shows error
print(dataValues)
let name = dataValues.object(forKey: "description")
self.nameArray.insert(name as! String, at: x)
}
Response from webservice
{
"result": [
{
"id": "1",
"title": "Mental Health",
"description": "<p>Mental health<\/p>",
"date": "22 Jul 2015",
"image": "image1444714284.jpg",
"status": "0"
},
{
"id": "2",
"title": "Olive oil: The healthiest fat is also harmful for you",
"description": "<p>ssss<\/p>",
"date": "16 Jul 2015",
"image": "image1444714355.jpg",
"status": "1"
},
{
"id": "3",
"title": "Jogging:Find the best fitness friend",
"description": "<p>ji<\/p>",
"date": "16 Jul 2015",
"image": "image1444714465.jpg",
"status": "1"
},
{
"id": "4",
"title": "Stock up on these",
"description": "<p>fffffffff<\/p>",
"date": "15 Jul 2015",
"image": "image1444715133.jpg",
"status": "1"
},
{
"id": "5",
"title": "Pick your perfect tunes",
"description": "<p>fffffffff<\/p>",
"date": "15 Jul 2015",
"image": "image1444715295.jpg",
"status": "0"
},
{
"id": "6",
"title": "Buy comfy sneaks",
"description": "<p>h<\/p>",
"date": "22 Jul 2015",
"image": "image1444715388.jpg",
"status": "1"
},
{
"id": "7",
"title": "Eat this, run that",
"description": "<p>rrrrrr<\/p>",
"date": "9 Jul 2015",
"image": "image1444715465.jpg",
"status": "1"
},
{
"id": "8",
"title": "Say hello to H20",
"description": "<p>jkjk<\/p>",
"date": "10 Jul 2015",
"image": "image1444715515.jpg",
"status": "1"
},
{
"id": "11",
"title": "gfhsh",
"description": "<p>sdhsgh fgdfgdgdf<\/p>",
"date": "17 Dec 2015",
"image": "image1450263806.jpg",
"status": "1"
},
{
"id": "12",
"title": "test",
"description": "<p>dfsdfsdffds<\/p>",
"date": "16 Dec 2015",
"image": "image1450264678.jpg",
"status": "1"
}
],
"status": true,
"message": "Health Tips List..."
}
Try this
var desriptionArray = [String]()
for dataValues in responseObject["result"] as! [[String: AnyObject]] {
let name = dataValues ["description"] as! String
desriptionArray .append(name)
}
OR
for (index , element) in (responseObject["result"] as! [Any]).enumerated() {
let nameDict = element as! [String : AnyObject]
let strDecription = nameDict["description"] as! String
desriptionArray .insert(strDecription, at: index)
}