I am working in an application need to check a particular key value I will paste my JSON response of [[String: Any]] type. but I could not check it or else could not fetch the status key from the array.
[
{
"updated_by": <null>,
"created_at": 2018-12-26T07:28:04.000Z,
"deleted_by": <null>,
"status": Request,
"friend_id": 139,
"user_id": 141,
"id": 53,
"created_by": 141,
"deleted_at": <null>,
"is_deleted": 0,
"updated_at": <null>
}
]
I need to take "status": Request this field alone from the response and I need to check it.
For example:
if status == "Request"{
//need to do some task
} else {
//need to do some
}
I'll throw in another solution, using filter to find the desired status:
let requests = array.filter { $0["status"] as? String == "Request" }})
Where requests will contain any status == "Request" requests.
Try looping through items:
for dictionary in dict {
if let status = dictionary["status"] as? String, status == "Request" {
// Status is found
} else {
// Not found
}
}
Related
I'm just starting my way in programming, and I'm stuck with the problem of pulling parameters out of JSON.
Here is what a JSON file looks like:
{
"results": 1,
"data": [
{
"wind": {
"degrees": 220,
"speed_kts": 4,
"speed_mph": 5,
"speed_mps": 2
},
"temperature": {
"celsius": 13,
"fahrenheit": 55
},
"dewpoint": {
"celsius": 12,
"fahrenheit": 54
},
"humidity": {
"percent": 94
},
"barometer": {
"hg": 29.85,
"hpa": 1011,
"kpa": 101.09,
"mb": 1010.92
},
"visibility": {
"miles": "Greater than 6",
"miles_float": 6.21,
"meters": "10,000+",
"meters_float": 10000
},
"elevation": {
"feet": 98.43,
"meters": 30
},
"location": {
"coordinates": [
-6.06011,
36.744598
],
"type": "Point"
},
"icao": "LEJR",
"observed": "2019-12-01T18:00:00.000Z",
"raw_text": "LEJR 011800Z 22004KT 9999 FEW020 13/12 Q1011",
"station": {
"name": "Jerez"
},
"clouds": [
{
"code": "FEW",
"text": "Few",
"base_feet_agl": 2000,
"base_meters_agl": 609.6
}
],
"flight_category": "VFR",
"conditions": []
}
]
}
I want to retrieve the barometric pressure in hPa (results => data => barometer => hpa).
And here is my code (I use Alamofire):
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("https://api.checkwx.com/metar/lejr/decoded", headers: headers).responseJSON { response in
// print(response)
if let metardataJSON = response.result.value {
let metarDataObject:Dictionary = metardataJSON as! Dictionary<String, Any>
print(metarDataObject)
let resultsObject:Dictionary = metarDataObject["results"] as! Dictionary<String, Any>
let dataObject:Dictionary = resultsObject["data"] as! Dictionary<String, Any>
let barometerObject:Dictionary = dataObject["barometer"] as! Dictionary<String, Any>
let hpaObject:NSNumber = barometerObject["hpa"] as! NSNumber
print(hpaObject)
}
}
After all the attempts, I cannot get rid of the error "Thread 1: signal SIGABRT":
Could not cast value of type '__NSCFNumber' (0x7fff87b9c520) to 'NSDictionary' (0x7fff87b9d5b0).
2019-12-01 19:34:18.723588+0100 Metar[6721:452116] Could not cast value of type '__NSCFNumber' (0x7fff87b9c520) to 'NSDictionary' (0x7fff87b9d5b0).
Can anyone shed some light on this issue and help me to improve my code?
Forgive me if the question seems simple or inappropriate - I'm just a beginner :)
Drop the first extraction line and refer to the metarDataObject in the second line. And note that inside "data" there is an array:
let dataObject:Dictionary = metarDataObject["data"] as! [[String: Any]]
let barometerObject:Dictionary = dataObject[0]["barometer"] as! [String: Any]
let hpaObject:NSNumber = barometerObject["hpa"] as! NSNumber
To not have to deal with these kinds of issues in the future I recommend to use some kind of "object mapping" framework which takes care of mapping the json into a useable, type-safe struct.
I am trying to make an API request to get an API response I am getting all the elements but I am facing braces issue I want a whole response and "order_devices" key, in {} braces but I am getting these in [] braces.
the array in which i am passing value,
var popUpArray :[[String:AnyObject]] = []
then on btn click i am saving values in dictionary
#IBAction func btnSave(_ sender: Any) {
let popupDict = (["quantity": Int(txtEnterQuantity.text!), "name": lblDeviceName.text,"id": deviceDict["id"], "region":1, "system_integrated":1 ])as! [String:AnyObject]
and then passing the same dictionary value as parameter
let passDict = [
"dealer_id":dropDownId!,
"client_id":dropDownId!,
"distributor_id":searchBarId!,
"emp_id":UserId,
"comments":CommentKey!,
"accepted_by":0,
"valid_from":strDate!,
"valid_upto": 0,
"order_devices":popupDict
] as [String : Any]
if Reachability.isConnectedToNetwork() {
showActivityIndicator()
Alamofire.request("http://13.232.230.41/IAC_CRM/public/api/createOrder", method: .post, parameters: passDict, encoding: JSONEncoding.default, headers: [:])
.responseJSON { (response) in
i am getting this response ,
[
"comments": "demo",
"dealer_id": 3,
"valid_from": "6-3-2019",
"distributor_id": 72,
"client_id": 3,
"accepted_by": 0,
"emp_id": 33,
"valid_upto": 0
"order_devices":
[
[
"id": 1,
"quantity": 10,
"region": 1,
"system_integrated": 1
]
,
[
"id": 2,
"quantity": 12,
"region": 1,
"system_integrated": 1
]
]
]
i want this response,
{ "dealer_id":"1", "client_id":"2", "distributor_id":"2",
"emp_id":"1", "comments":"IAC test device comments", "accepted_by":0,
"valid_from":"2019-01-24", "valid_upto":"1", "order_devices":[
{
"device_id":"1",
"quantity":"1", "region":1, "system_integrated":1
}
,
{
"device_id":"2",
"quantity":"1"
"region":1,
"system_integrated":1
}
] }
means i want whole response and "order_devices" key in "curly braces"{} .
There is nothing wrong with request or response, your are getting response what your API is returning, You should ask you backend developer Or Api Provider to Give you response in form of your requirement i mean proper formatted Right now its in form of Array.
Here I need to get the index of particular array in which the key value pair item.defaultShipping == "true" then I need to the get the index of particular array and to pass in model class so that in order to get corresponding data so that it should be passed in another Api but when I tried below method it showing an error that Contexual type 'Any' cannot be used within dictionary literal in let parameters below line can anyone help me how to resolve this issue ?
here is my code
var i = 0
for item in customerShippingAddressModel {
if item.defaultShipping == "true" {
}
i += 1
}
let arr = customerShippingAddressModel[i]
let parameters : [String: Any] = ["address":
[ "region": "\(arr.region.region)",
"region_code": "\(arr.region.regionCode)",
"region_id": "\(arr.region.regionId)",
"country_id": "\(arr.countryId)",
"company": "\(arr.company)",
"telephone": "\(arr.telephone)",
"postcode": "\(arr.postCode)",
"city": "\(arr.city)",
"firstname": "\(arr.firstName)",
"lastname": "\(arr.lastName)",
"email": "\(arr.email)",
"prefix": "",
"sameAsBilling": 1,
"street": ["0": "\((arr.customerStreet[0])!)",
"1": "\((arr.customerStreet[1])!)"]]]
print(parameters)
Since Swift 3 you can use enumerated() which will allow you to have the index and the value as the following:
for (index, item) in customerShippingAddressModel.enumerated() {
if item.defaultShipping == "true" {
// you can get the item and index value here.
}
}
I need create a json for send from a API REST:
{
"ownId": "seu_identificador_proprio",
"amount": {
"currency": "BRL",
"subtotals": {
"shipping": 1000
}
},
"items": [
{
"product": "Descrição do pedido",
"quantity": 1,
"detail": "Mais info...",
"price": 1000
}
],
"customer": {
"ownId": "seu_identificador_proprio_de_cliente",
"fullname": "Jose Silva",
"email": "nome#email.com",
"birthDate": "1988-12-30",
"taxDocument": {
"type": "CPF",
"number": "22222222222"
},
"phone": {
"countryCode": "55",
"areaCode": "11",
"number": "66778899"
},
"shippingAddress": {
"street": "Avenida Faria Lima",
"streetNumber": 2927,
"complement": 8,
"district": "Itaim",
"city": "Sao Paulo",
"state": "SP",
"country": "BRA",
"zipCode": "01234000"
}
}
}
I am confused with the creation..
I try begin with [NSObject:AnyObject]
var d1 : [NSObject:AnyObject] = ["ownId":"seu_identificador_proprio", "customer":""]
let dd1 = ["currency":"BRL"]
let dd2 = ["shipping":"1000"]
let arr = [d1]
let d = try! NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions.PrettyPrinted)
let s = NSString(data: d, encoding: NSUTF8StringEncoding)! as String
print(s)
But I need help!
I have updated your code and added some hints, how can you build the above listed structure. Happy coding!
// Do not use NSObject as key's type
// Keys in a dictionary are usually Strig in every language
var d1: [String: AnyObject] = ["ownId":"seu_identificador_proprio", "customer":""]
// Define the type of your dictionaries, if you dont, in this case it will create a [String:String] dictionary, but you need to insert an array into it
// Make it a var, so you can mutate the container
var dd1: [String: AnyObject] = ["currency":"BRL"]
// Here the type is undefined. Try inserting anything else than String, and see the results
let dd2 = ["shipping":"1000"]
dd1["subtotals"] = dd2
d1["amount"] = dd1
// Build all your dictionaries like i did above, and at the end add all of them into arr
let arr = [d1]
// Do not force try any throwing function in swift - if there is an error, your application will crash
// Use proper error handling - https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
do {
let d = try NSJSONSerialization.dataWithJSONObject(arr, options: NSJSONWritingOptions.PrettyPrinted)
let s = NSString(data: d, encoding: NSUTF8StringEncoding)! as String
print(s)
} catch {
// Do your error handling here
}
I am trying to loop through an array inside an array. The first loop was easy but I'm having trouble looping through the second array inside it. Any suggestions would be welcome!
{
"feeds": [
{
"id": 4,
"username": "andre gomes",
"feeds": [
{
"message": "I am user 4",
"like_count": 0,
"comment_count": 0
}
]
},
{
"id": 5,
"username": "renato sanchez",
"feeds": [
{
"message": "I am user 5",
"like_count": 0,
"comment_count": 0
},
{
"message": "I am user 5-2",
"like_count": 0,
"comment_count": 0
}
]
}
]
}
As you see I'm having trouble to reach through to the message field etc
Here's my code on swiftyjson
let json = JSON(data: data!)
for item in json["feeds"].arrayValue {
print(item["id"].stringValue)
print(item["username"].stringValue)
print(item["feeds"][0]["message"])
print(item["feeds"][0]["like_count"])
print(item["feeds"][0]["comment_count"])
}
The output I get is
4
andre gomes
I am user 4
0
0
5
renato sanchez
I am user 5
0
0
As you see I'm unable to get the message"I am user 5-2" and corresponding like_count and comment_count
You already demonstrated how to loop through a JSON array so you only need to do it again with the inner feeds:
let json = JSON(data: data!)
for item in json["feeds"].arrayValue {
print(item["id"].stringValue)
print(item["username"].stringValue)
for innerItem in item["feeds"].arrayValue {
print(innerItem["message"])
print(innerItem["like_count"])
print(innerItem["comment_count"])
}
}
If you only want the first item in the inner feeds array, replace the inner for lop with this:
print(item["feeds"].arrayValue[0]["message"])
print(item["feeds"].arrayValue[0]["like_count"])
print(item["feeds"].arrayValue[0]["comment_count"])