I'm new to using Alamofire and have encountered an issue. I'm able to run the following code to print out all the data from an API endpoint.
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let JSON = response.result.value {
print(JSON)
}
}
The issue is that when I run this:
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let JSON = response.result.value {
print(JSON["firstkey"])
}
}
I get the error:
Type 'Any' has no subscript members
I don't know why this error is happening, it seems as if I'm accessing the data correctly. Any help would be great, thanks!
I have tried formatting it using both:
print(JSON["firstkey"] as String)
and
print(JSON["firstkey"] as [String:Any]
but they still give the same error.
This is the JSON on my endpoint:
{
"firstkey":"it worked!",
"secondkey":["item1", "item2", "item3"]
}
This is really simple. You just need to force cast (as!) your JSON. so change your code to this and it will work:
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let JSON = response.result.value {
let json = JSON as! [String: Any]
print(json["firstkey"])
}
}
Edit 1:
As you said in comments that you are using SwiftyJSON package. Sample code is as follows:
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
print(json["firstkey"].stringValue)
}
}
Alamofire.request("https://mmcalc.com/api").responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
print(json.arrayValue[0]["uniqueUsers"].stringValue)
}
}
You are trying to get the value with getting the object, try this:
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON["firstkey"])
}
}
Hope it will work!
You should add ! at the end of code before ) to force unwrap the value
Alamofire.request("http://codewithchris.com/code/afsample.json").responseJSON { response in
if let JSON = response.result.value {
let json = JSON as! [String: Any]
print(json["firstkey"]!)
}
}
Related
I'm calling an api in swift 3. And from the api I'm getting response in JSON String format. How to convert that JSON String to Dictionary or Array in Swift. Also that JSON string contains further array's and dictionaries.
I've tried using EVReflection tool. It's only converting the upper JSON object in dictionary. The nested dictionaries and array's are still in String format.
Try something like this, response is [String: Any] so you must cast to a any type
DispatchQueue.main.async {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
let j = json as NSDictionary
guard let resp = response as? HTTPURLResponse
else {
// No response from server
return
}
if resp.statusCode == 200 {
// You can put here some callback, this is a data you need
} else {
// Here is some error
}
}
} catch {
// And this is a error from server
}
}
You should receive jsonData which you can directly try JSONSerialization.
If for any reason you receive it as json String then you have to convert that string to jsonData first
// Here you have to convert Json String to jsonData
// if it's not Json String then skip this line
let jsonData = jsonString.data(using: .utf8)
// Try to convert it to json object
do {
let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [String : Any]
// now you can try to parse your json
} catch let error as NSError {
print(error.localizedDescription)
}
Or as #Jay mentioned use Swiftyjson
Using below code to parse JSON , facing issue
let result = "{
status = ok;
token = XXXXX;
}"
do {
let json = try JSONSerialization.jsonObject(with: (result as? Data)! , options: JSONSerialization.ReadingOptions())
print("Further data \(json)")
} catch {
print(error)
}
}
Facing below exception:
Could not cast value of type '__NSDictionaryI' (0x111789238) to
'NSData' (0x1117882e8). (lldb)
Any help is really appreciated.
First, JSON format is not correct. It should as
{
"status":"ok",
"token":"XXXXX"
}
Second, You are trying typecast string into NSData which is not possible. Issue is at
(result as? Data)!
Rather you should do it like this:
let resultData = result.data(using: String.Encoding.utf8)
I am stuck with parsing JSON with AlamoFire and SwiftyJSON for iOS. I have a JSON such as this one:
[{"id":23561,"name":"RFI - Persan رادیو صدای Ùرانسه Ùارسی","country":"FR","image":{"url":null,"thumb":{"url":null}},"slug":"rfi-persan-رادیو-صدای-Ùرانسه-Ùارسی","website":"rfi","twitter":"","facebook":"","categories":[{"id":21,"title":"News","description":"","slug":"news","ancestry":"4"}],"streams":[{"stream":"http://rfi-persan.scdn.arkena.com/rfienpersan.mp3","bitrate":0,"content_type":"audio/mpeg","status":1}],"created_at":"2016-01-12T07:52:08+01:00","updated_at":"2016-08-02T01:52:50+02:00"}]
This is what I´ve tried so far, but doesn't work:
func loadSomeJSONData() {
Alamofire.request(.GET, "http://example.com/json/")
.responseJSON { (_, _, data, _) in
let json = JSON(data!)
if let Name = json["name"].string {
println("name: \(firstName)") // Name should equal "RFI"
}
}
}
But for some reason it doesn't get name from json object.
Thank you very much!
Your json is Array not Dictionary, so access the json this way
if let arr = json.arrayObject as? [[String:AnyObject]] {
if let name = arr[0]["name"] as? String {
println("name: \(name)") // Name should equal "RFI"
}
}
I am using Alamofire to parse a JSON API, however, I can't figure out how to parse the response data from Alamofire.
When I try to loop through the fetched data, XCode gives me "Segmentation Fault: 11" error.
Here is my current code:
var tableData:NSArray // I have tried several variable types, NSDictionary, String etc.
--
override func viewDidLoad() {
super.viewDidLoad()
self.getJsonData()
}
func getJsonData() {
Alamofire.request(.GET, "https://hotell.difi.no/api/json/mattilsynet/smilefjes/tilsyn", parameters: [:])
.responseJSON { response in
if let JSON = response.result.value {
// print("JSON: \(response.result)")
for entry in JSON["entries"] {
print("\(entry)") // this is where everything crashes
}
}
self.doTableRefresh()
}
}
func doTableRefresh() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
What is the correct data format for this JSON result: https://hotell.difi.no/api/json/mattilsynet/smilefjes/tilsyn ? And how do I take the data and populate the tableview?
Convert the response to NSDictionary and NSArray:
func getJsonData() {
Alamofire.request(.GET, "https://hotell.difi.no/api/json/mattilsynet/smilefjes/tilsyn", parameters: [:])
.responseJSON { response in
if let JSON = response.result.value as? NSDictionary{
if let entries = JSON["entries"] as? NSArray{
for entry in entries {
if let entry = entry as? NSDictionary {
for (key, value) in entry {
print("\(key) - \(value)")
}
}
}
}
}
}
}
Without using SwiftyJSON, the idea is to know the right type for each object and successfully downcast.
response.result.value is a dictionary: [String:AnyObject], and the content of json["entries"] is an array of dictionaries: [[String:AnyObject]]. Etc.
Example:
func getJsonData() {
Alamofire.request(.GET, "https://hotell.difi.no/api/json/mattilsynet/smilefjes/tilsyn", parameters: [:])
.responseJSON { response in
if let json = response.result.value as? [String:AnyObject] {
if let entries = json["entries"] as? [[String:AnyObject]] {
for entry in entries {
print(entry) // each entry is a dictionary of type [String:AnyObject]
}
// example of accessing an entry:
if let firstEntry = entries.first, value = firstEntry["adrlinje1"] as? String {
print(value) // "Christian IV gate 3"
}
}
}
}
}
You have to specify the type of your expected value (With SwiftyJSON):
for entry in JSON["entries"] { // Here
print(entry.stringValue)
}
I tried to get the value of "seed" from json response. But i am getting nil.
Json Response:
{
"response": {
"params": {
"rows": "20",
"defType": "abc",
"seed": "381786611"
}
}
}
Swift Parsing:
if let responseHeader:AnyObject = object?["response"] as? NSDictionary {
if let t = (responseHeader["params"] as? NSDictionary){
let t1 = t["seed"] as? String
println("result is \(t1)") // This returns nil
}
}
Json Parsing
func processJsonToDictionary(object:AnyObject?) -> AnyObject?{
if object != nil {
if let data: AnyObject = object {
var parseError: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(object as NSData!, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary
if(parseError != nil){
return parseError
}
else{
return jsonResult
}
}
}
return nil
}
I am not able to get the value of t1. it always returns nil.
How can i get the value.
Also, I put a breakpoint and tried to print the value of t1. But the Xcode Keeps crashing. Why?
I think the major problem here is only accessing a JSON object in swift.
var error: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
let resp = jsonDict["response"] as? NSDictionary
let params = resp?["params"]?["seed"]
let seed = params!! as NSString
This is just to show you how a JSON object is accessed in swift. You can ofcourse change it according to your needs to remove unwanted Optional Chaining.
For easy JSON manipulation in Swift you could try this little library. It seems pretty easy and you could do this:
var dictionary: [String: AnyObject]!
if let json = NKJSON.parse(yourNSDataObject) {
dictionary <> json[NKJSON.rootKey]
}
First confirm that the response which you are getting is in json format or in string format.
For json parsing you can use swifty json pod