How I can parse JSON with alamofire
Your response is a JSON Object known as Dictionary, use following line
let itemObject = response.result.value as? [String : Any]
go ahead with parsing inner array items
if let array = itemObject?["items"] as? [[String : Any]] {
for dict in array {
guard
let id = dict["id"] as? Int,
let name = dict["name"] as? String,
let owner = dict["owner"] as? [String : Any],
let ownerId = owner["id"] as? Int
else {
print("Error parsing \(dict)")
continue
}
print(id, ownerId, name)
}
}
Instead of parsing JSON manually, use Codable
with Alamofire's responseData
, below is an example
struct Item: Decodable {
let id: Int
let name: String
let owner: Owner
}
struct Owner: Decodable {
let id: Int
let login: String
}
struct PageData: Decodable {
let totalCount: Int
let incompleteResults: Bool
let items: [Item]
enum CodingKeys: String, CodingKey {
case totalCount = "total_count"
case incompleteResults = "incomplete_results"
case items
}
}
Alamofire.request("URL").responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
do {
let pageData = try JSONDecoder().decode(PageData.self, from: data)
print(pageData, pageData.items.first?.name ?? "", pageData.items.first?.owner.id ?? 0)
} catch let error {
print(error)
}
}
}
How to parse JSON response to Model struct from Alamofire in Swift 5?
Assuming your RegisterResponse
is Decodable
, simply use responseDecodable
:
AF.request(registerUrl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
.responseDecodable(of: RegisterResponse.self) { response in
// Handle response.
}
Parse alamofire response into JSON return nil
This xjson
is an Array
of JSON
(looks User) objects. So you need to access the array elements as below,
let xjson : JSON = JSON(res.value)
if let firstUser = xjson.array?.first {
print(firstUser["firstName"] as? String)
}
You can also put your JSON
response here and get the required data types and decoding code for free.
JSON Array to model using Alamofire
If you really want a model class then decode as already suggested into a String array and then map the result to your model
struct Category {
let name: String
}
AF.request(url).responseDecodable(of: [String].self) { response in
guard let categories = response.value else {
return
}
DispatchQueue.main.async { [weak self] in
self.category = categories.map(Category.init)
self?.tableView.reloadData()
}
}
Related Topics
Setting Custom Uitableviewcells Height
Undocumented Nsurlerrordomain Error Codes (-1001, -1003 and -1004) Using Storekit
iOS 7 Tableview Like in Settings App on iPad
Draw Segments from a Circle or Donut
iPhone Sdk: Differencebetween Loadview and Viewdidload
iOS Detect If User Is on an iPad
How to Export "Fat" Cocoa Touch Framework (For Simulator and Device)
How to Create .Ipa File Using Xcode
Uiview and Initwithframe and a Nib File. How to Get the Nib File Loaded
How to Determine Whether Code Is Running in Debug/Release Build
Nsurlconnection Using iOS Swift
How to Recognize Swipe in All 4 Directions
Error: "The Sandbox Is Not in Sync with the Podfile.Lock..." After Installing Restkit with Cocoapods
Sqlite File Location Core Data
iOS (Iphone, iPad, Ipodtouch) View Real-Time Console Log Terminal