I have been searching for days to convert a fairly simple JSON string to an object type in Swift but with no avail.
Here is the code for web service call:
For iOS 10 & Swift 3, using Alamofire & Gloss:
Alamofire.request("http://localhost:8080/category/en").responseJSON { response in
if let data = response.data {
if let categories = [Category].from(data: response.data) {
self.categories = categories
self.categoryCollectionView.reloadData()
} else {
print("Casting error")
}
} else {
print("Data is null")
}
}
and here is the Category class
import Gloss
struct Category: Decodable {
let categoryId: Int?
let name: String?
let image: String?
init?(json: JSON) {
self.categoryId = "categoryId" <~~ json
self.name = "name" <~~ json
self.image = "image" <~~ json
}
}
IMO, this is by far the most elegant solution.