How to Parse Json Response from Alamofire API in Swift

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



Leave a reply



Submit