Swift ios parse json data get only selected data - ios

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)
}
}

Related

Swift Nested jSON Decode

I have problem with nested json decoding. Im getting no error but response is empty { }. Down bellow is my sample json and struct.
{
"categories": [
{
"ID": 130,
"data": [
{
"en": [
{
"title": "test"
}
],
"fr": [
{
"title": "teste"
}
]
}
],
"lifts": [
{
"ID": 104,
"data": [
{
"en": [
{
"code": "test",
"title": "test"
}
],
"fr": [
{
"code": "test",
"title": "test"
}
]
}
]
},
{
"ID": 105,
"data": [
{
"en": [
{
"code": "test",
"title": "test"
}
],
"fr": [
{
"code": "test",
"title": "test"
}
]
}
]
}
]
}
And this is my struct
struct jsonResponse : Codable {
struct Categories : Codable {
let id : Int
let data : [LanguageData]
let lifts : [Lifts]
struct LanguageData : Codable {
let en, fr : [Data]
struct Data : Codable {
let code : String?
let title : String?
}
}
struct LiftsData : Codable {
let id : Int
let data : [LanguageData]
}
}
Then Im trying to decode JSON like this:
let lifts = try JSONDecoder().decode(jsonResponse.self, from: data)
But when I print lifts, i see only empty {}. Also no error message during decoding, so have no idea what can be wrong.

how to set json data in table view [closed]

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.

How to retrieve data from json response

I am trying to get data from json response, and the response format is mentioning below. I want to fetch "recipient" dictionary, and need to show in table.each cell contains name and unique id and image. How to get this dictionary to story in local dictionary?
{
"success": 1,
"status": 200,
"data": {
"chat": [
{
"id": 5,
"status": 0,
"created_at": "2019-02-19 13:29:15",
"updated_at": "2019-02-19 13:29:15",
"recipient": {
"id": 5,
"unique_id": "10004",
"name": "Pandu",
"avatar": "https://www.planetzoom.co.in/img/default_avatar_female.png"
},
"conversation": {
"id": 67,
"chat_id": 5,
"user_id": 4,
"type": 0,
"message": "I have sent a msg now",
"status": 0,
"created_at": "2019-02-26 04:02:20"
}
},
{
"id": 3,
"status": 0,
"created_at": "2019-02-19 13:17:49",
"updated_at": "2019-02-19 13:17:49",
"recipient": {
"id": 8,
"unique_id": "10007",
"name": "Mahitha",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/cZt9yQlBzIEewOdQ1lYZhl3dFiOv2k3bxG7HLOzR.jpeg"
},
"conversation": {
"id": 57,
"chat_id": 3,
"user_id": 4,
"type": 0,
"message": "Hi",
"status": 0,
"created_at": "2019-02-24 13:04:29"
}
},
{
"id": 2,
"status": 0,
"created_at": "2019-02-19 07:59:05",
"updated_at": "2019-02-19 07:59:05",
"recipient": {
"id": 1,
"unique_id": "1111",
"name": "Angadi World Tech",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/NlVzdUAfmLfIG9677szYZz7NkWyY4ULHAqnlCiiV.png"
},
"conversation": {
"id": 21,
"chat_id": 2,
"user_id": 4,
"type": 0,
"message": "Hi\\uD83D\\uDE0A",
"status": 0,
"created_at": "2019-02-21 10:35:26"
}
}
]
}
}
The best way to decode json in my opinion is to use Codable
I've created a few structs to represent the data and to decode it, please note this json wasn't valid so have had to wrap it in {}
Here's the json:
let jsonString = """
{
"chat": [
{
"id": 12,
"status": 0,
"created_at": "2019-02-22 04:57:12",
"updated_at": "2019-02-22 04:57:12",
"recipient": {
"id": 26,
"unique_id": "10024",
"name": "Kaverinew",
"avatar": "https://www.planetzoom.co.in/storage/user/avatar/1PyI4ceM3zPsG1fxbfatktWUT75sOE2Ttah8ctIp.png"
},
"conversation": {
"id": 65,
"chat_id": 12,
"user_id": 4,
"type": 1,
"message": "https://www.planetzoom.co.in/storage/chat/message/e759KWdSBegwXslAoS2xst0lohbbjNZMdpVnbxQG.png",
"status": 0,
"created_at": "2019-02-25 15:39:24"
}
},
{
"id": 6,
"status": 0,
"created_at": "2019-02-20 07:16:35",
"updated_at": "2019-02-20 07:16:35",
"recipient": {
"id": 7,
"unique_id": "10006",
"name": "Hema",
"avatar": "https://www.planetzoom.co.in/img/default_avatar_female.png"
},
"conversation": {
"id": 44,
"chat_id": 6,
"user_id": 4,
"type": 1,
"message": "https://www.planetzoom.co.in/storage/chat/message/qJjOtCRcBKBuq3UKaKVuVOEIQhaVPeJr3Bd4NoLo.png",
"status": 0,
"created_at": "2019-02-22 10:17:49"
}
}
]
}
Here are the structs:
struct Recipient: Codable {
var identifier: Int
var unique_id: Int
var name: String
var avatar: String
enum CodingKeys: String, CodingKey {
case identifier = "id"
case unique_id = "unique_id"
case name = "name"
case avatar = "avatar"
}
}
struct Conversation: Codable {
var identifier: Int
var chat_id: Int
var user_id: Int
var conversationType: Int
var message: String
var status: Int
var created_at: String
enum CodingKeys: String, CodingKey {
case identifier = "id"
case chat_id = "chat_id"
case user_id = "user_id"
case conversationType = "type"
case message = "message"
case status = "status"
case created_at = "created_at"
}
}
struct Chat: Codable {
var identifier: Int
var status: Int
var created_at: String
var updated_at: String
enum CodingKeys: String, CodingKey {
case identifier = "id"
case status = "status"
case created_at = "created_at"
case updated_at = "updated_at"
}
}
struct RootObject: Codable {
var chats: [Chat]
enum CodingKeys: String, CodingKey {
case chats = "chat"
}
}
And here is how you decode it:
if let jsonData = jsonString.data(using: .utf8) {
do {
let root = try JSONDecoder().decode(RootObject.self, from: jsonData)
} catch {
print(error)
}
}
Assuming you already have a Data object representing your JSON you can use JSONSerialization to convert it to concrete Swift object. Once that is done you simply need to go step by step and extract the data. Something like the following should work nicely:
func retrieveRecipients(jsonData: Data?) throws -> [[String: Any]] {
guard let data = jsonData else { throw NSError(domain: "Parsing Recipients", code: 404, userInfo: ["dev_message": "Null JSON data inserted"]) }
guard let parsedJSON = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else { throw NSError(domain: "Parsing Recipients", code: 500, userInfo: ["dev_message": "Data could not be parsed as JSON"]) }
guard let object = parsedJSON as? [String: Any] else { throw NSError(domain: "Parsing Recipients", code: 500, userInfo: ["dev_message": "Parsed JSON is not a dictionary"]) }
guard let items = object["chat"] as? [[String: Any]] else { throw NSError(domain: "Parsing Recipients", code: 404, userInfo: ["dev_message": "JSON is missing \"chat\" array"]) }
return items.compactMap { $0["recipient"] as? [String: Any] }
}
This is all the safety enabled. Otherwise you could do it very shortly:
func retreiveRecipientsStrict(jsonData: Data?) -> [[String: Any]] {
return ((try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: Any])["chat"] as! [[String: Any]]).compactMap { $0["recipient"] as? [String: Any] }
}
But this will crash if there is a mistake and it will be extremely hard to debug what went wrong.

How to parse particular JSON in Swift

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"
}
}

way to get value for address in this case? [closed]

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"];

Resources