Parsing JSON Using the New Swift 3 and Alamofire

Parsing JSON using the new Swift 3 and Alamofire

As you can see in Alamofire tests you should cast response.result.value to [String:Any]:

if let json = response.result.value as? [String: Any] {
// ...
}

How to parse this json with Alamofire 4 in Swift 3?

This was the parse json function I eventually came up with. The problem for this json data is that it is a dictionary inside an array. I am a noob and most of the answers and how tos I saw would not fit my json data. Here is the function I finally came up with with worked.

var myItems = [[String:Any]]()

then in my view controller class

func loadMyItems() {

Alamofire.request(myItemsURL)
.responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)

self.collectionView.reloadData()
})
}

func parseData(JSONData: Data) {
do {
let readableJSON = try JSONSerialization.jsonObject(with: JSONData, options:.allowFragments) as! [String: Any]

let items = readableJSON["items"] as! [[String: Any]]

self.myItems = items

}
catch {
print(error)
}
}

func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as? myCell

let dictionary = myItems[indexPath.row] as [String:Any]
if let item_title = dictionary["item_title"] as? String {
cell!.textLabel.text = item_title
print(item_title)
}

return cell!
}

How to Parse JSON in Swift 3 using Alamofire?

The value for key pages is a dictionary, not an array and it derives from query.

Please read the JSON: [] is array {} is dictionary.

And there is no key id, it's pageid and the value is an Int (no double quotes).

         if let pages = query["pages"] as? JSONStandard {
print(pages," Check this! ")
for (_, page) in pages {
let id = page ["pageid"] as! Int
print(id)
titles.append("\(id)")
}
self.tableView.reloadData() // don't reload the table view in the loop.
}

or – easier – take the key of the dictionary which is also the id number (here indeed as String)

         if let pages = query["pages"] as? JSONStandard {
print(pages," Check this! ")
for (id, page) in pages {
print(id)
titles.append(id)
}
self.tableView.reloadData()
}

Be aware that a dictionary is always unordered.

Trying to parse JSON in Swift 3 using Alamofire

Based on the comments I understand that the structure actually looks like this:

[{
outer = {
height = 3457;
width = 2736;
};
cost = 220;
name = "Mega";
},
{
outer = {
height = 275;
width = 300;
};
cost = 362;
name = "Ultra";
}]

I still don't fully understand what you are hoping to do with all these variables, but here is how you parse them to print the height value for each section, as that is what you seem to be trying to do in the examples:

//Here you safely unwrap all of the sections as an array of dictionaries
if let allSections = response.result.value as? [[String : Any]] {

//Here we will loop through the array and parse each dictionary
for section in allSections {
if let cost = section["cost"] as? Int, let name = section["name"] as? String, let outer = section["outer"] as? [String : Any], let height = outer["height"] as? Int, let width = outer["width"] as? Int {
//Inside here you have access to every attribute in the section

print(height)
}
}
}

Json Parsing in swift 3 using Alamofire

First of all in Swift use Swift's native Array and Dictionary instead of NSDictionary and NSArray.

Now to get name you need to get Data array from your JSON response Dictionary. So try something like this.

Alamofire.request( HeadersClass.api.domainName + "OrderTable", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HeadersClass.allHeaders.headers).responseJSON { response in

//debugPrint(response)
if let jsonDict = response.result.value as? [String:Any],
let dataArray = jsonDict["data"] as? [[String:Any]] {
let nameArray = dataArray.flatMap { $0["name"] as? String }
print(nameArray)
}
}

Output

["TestMan", "tommy", ...]

How to parse JSON using Alamofire in Swift 3.0 without any third-party library

Top level json is [String:Any] and main is an array i.e. [[String:String]]

    Alamofire.request("myurl") .responseJSON { response in
if let result = response.result.value as? [String:Any],
let main = result["main"] as? [[String:String]]{
// main[0]["USDARS"] or use main.first?["USDARS"] for first index or loop through array
for obj in main{
print(obj["USDARS"])
print(obj["date"])
}
}
}

Parse JSON data with Swift, AlamoFire and SwiftyJSON

Can you try

if let result = response.result.value as? [String:Any] {
if let contact = result["contact"] as? [String:Any] {
if let first = contact["first"] as? String {
print(first)
}
}
}

also this

let data = JSON(data: JSON)

gives error because parameter should be of type Data not Dictionary

I would prefer to return Data from Alamofire request and use Decodable to parse it and convert to required model

Parsing JSON in Swift with Alamofire

Better not to use NS classes with Swift wherever possible. So instead of NSArray use Array.

To get smoothedPosition you need to parse more. tags gives you an array of dictionaries, so you need to loop array and get each dictionary inside tags array. Then finally you can get your smoothedPosition array.

func newTest() {
Alamofire.request(url).responseJSON { (response) in
if let newjson = response.result.value as? [String: Any], if let tagArray = newjson["tags"] as? [[String: Any]] {
for object in tagArray {
if let smoothedPosition = object["smoothedPosition"] as? [Double] {
print(smoothedPosition)
}
}
}
}
}
  • Also you should read more about codables to parse nested data and learn about optional binding and chaining to prevent crashes when you force (!) something which could be nil at some point.

  • You can use this site to check the possible Codable structure as per your response: https://app.quicktype.io/

JSON data not parsing using with Alamofire in swift3

You are passing wrong type in 1 param in call it should be URLConvertible(string or URL) not URLRequest. try below code.

let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]
let url = URL(string: "http://www.kids.com/rk/api/usersignin")!
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseJSON { response in

}

____________Edit___________

here header is post request headers(if any) or nil

let params: [String: Any] = ["email": username, "passCode": passwordstring, "deviceType": "IOS","deviceId":deviceId]

let urlString = "http://www.kids.com/rk/api/usersignin"
guard let url = URL(string: urlString), var request = try? URLRequest(url: url, method: .post, headers: header) else{
//
return
}

request.httpBody = params.map{ "\($0)=\($1)" }.joined(separator: "&").data(using: .utf8)
Alamofire.request(request).responseJSON { response in

}


Related Topics



Leave a reply



Submit