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.
Related
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'm new here. How to write and turn the code below into postString as I need to do submisson to API.
{
"service": 0,
"size": "string",
"orderReference": "string",
"dropOffHubId": "string",
"pickUpHubId": "string",
"courierId": "string",
"from": {
"address": {
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
}
},
"to": {
"name": "string",
"phone": "string",
"email": "string",
"address": {
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
}
}
}
Am I correct if I write it in this way, but how to put in the string after "from": { and also "address": { then go into "address1": "string", Then another one is "to": { "name": "string", then go inside
"address": {, then go inside "address1": "string",
let postString = [ "service": 0,
"size": "string",
"orderReference": "string",
"dropOffHubId": "string",
"pickUpHubId": "string",
"courierId": "string",
"from": "fromAddArr",
"to": "toAddArr"] as [String : Any]
var request = URLRequest(url:URL!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(bearerToken!, forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
I only know to write in this way.
{
"refNo": "string",
"code": "string"
}
let postString = ["refNo": "string",
"code": "string"]
Try this one i think you want something like this : First take dictionary of address from current json and convert that dictionary into string :
let dictionary:[String:Any] = ["address": [
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
]
]
if let theJSONData = try? JSONSerialization.data( withJSONObject: dictionary, options: []) {
let theJSONText = String(data: theJSONData, encoding: .utf8)
print("JSON string = \(theJSONText!)") //you can use this string to create dictionary as you want
let dict = ["addres":theJSONText!]
print(dict)
}
You do not need to write that string by yourself. If you are using swift 3 and have a model class for that JSON string, you can use a third party lib here. This will convert your model into dictionary, array, json string and data etc. You just need to make your model child of ParsableModel or JSONParsable.
If you have problem in creating model class from JSON you can use this utility. This will generate model class for your JSON:
class RootClass {
var courierId: String?
var dropOffHubId: String?
var from: From?
var orderReference: String?
var pickUpHubId: String?
var service: NSNumber?
var size: String?
var to: To?
}
class To {
var address: Addres?
var email: String?
var name: String?
var phone: String?
}
class From {
var address: Addres?
}
class Addres {
var address1: String?
var address2: String?
var city: String?
var country: String?
var postcode: String?
var state: String?
}
If you are using Swift 4. It provides you classes to Encode and Decode your code from JSON to model and model to JSON. You can save your time by using this.
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)
}
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"];