Jestem nowy w szybkim tempie, używając narzędzia json4swift do stworzenia klasy modelu. Chciałbym wiedzieć, jak uzyskać dane z klasy modelu, udało mi się zmapować elementy do klasy modelu za pomocą poniższego kodu.
let responseModel = Json4Swift_Base(dictionary: searchResultsData)
Mój json odpowiada za folllows:
{
"success": true,
"categorys": [
{
"categoryId": 1,
"categoryName": "Electricians "
},
{
"categoryId": 2,
"categoryName": " Drivers "
},
{
"categoryId": 3,
"categoryName": " Plumbers "
},
{
"categoryId": 4,
"categoryName": "Carpenters "
},
{
"categoryId": 5,
"categoryName": "Automobile works "
}
]
}
Narzędzie Json4swift wykonało dwie klasy, mianowicie klasę Json4Swift_Base i klasy. Muszę dostać z klasy modelu.
Odpowiedzi:
1 dla odpowiedzi № 1Jeśli chcesz nauczyć się Swift, proponuję zapomnieć o json4swift.
Najpierw musisz zbudować własne modele: Category
i Response
Kategoria:
struct Category {
let id: Int
let name: String
}
Odpowiedź:
struct Response {
let success: Bool
let categories: [Category]
}
Po drugie, chcesz zainicjować swoje modele za pomocą JSON. Stworzymy dla tego protokół:
typealias JSONDictionary = [String : Any]
protocol JSONDecodable {
init?(dictionary: JSONDictionary)
}
Twoje modele muszą implementować ten protokół, więc dodajemy rozszerzenia:
Rozszerzenie kategorii:
extension Category: JSONDecodable {
init?(dictionary: JSONDictionary) {
guard let id = dictionary["categoryId"] as? Int,
let name = dictionary["categoryName"] as? String else {
return nil
}
self.id = id
self.name = name
}
}
Rozszerzenie odpowiedzi:
extension Response: JSONDecodable {
init?(dictionary: JSONDictionary) {
guard let success = dictionary["success"] as? Bool,
let jsonCategoriesArray = dictionary["categorys"] as? [JSONDictionary] else {
return nil
}
self.success = success
self.categories =
jsonCategoriesArray.flatMap{ jsonCategoryDictionary in
Category(dictionary: jsonCategoryDictionary)
}
}
}
Teraz możesz napisać:
let response = Response(dictionary: jsonResponse)
if let response = response {
let success = response.success
let categories = response.categories
let firstCategory = categories[0]
// ...
}