-
-
Save hamishknight/9b5c202fe6d8289ee2cb9403876a1b41 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ServerResponse { | |
var id: Int | |
var username: String | |
var fullName: String | |
var reviewCounts = [Int]() | |
} | |
extension ServerResponse : Decodable { | |
private enum CodingKeys : String, CodingKey { | |
case id, user, reviewsCount = "reviews_count" | |
enum User : String, CodingKey { | |
case username = "user_name", realInfo = "real_info" | |
enum RealInfo : String, CodingKey { | |
case fullName = "full_name" | |
} | |
} | |
enum ReviewsCount : String, CodingKey { | |
case count | |
} | |
} | |
init(from decoder: Decoder) throws { | |
// top-level container | |
let container = try decoder.container(keyedBy: CodingKeys.self) | |
self.id = try container.decode(Int.self, forKey: .id) | |
// container for { "user_name": "Tester", "real_info": { "full_name": "Jon Doe" } } | |
let userContainer = try container.nestedContainer(keyedBy: CodingKeys.User.self, forKey: .user) | |
self.username = try userContainer.decode(String.self, forKey: .username) | |
// container for { "full_name": "Jon Doe" } | |
let realInfoContainer = try userContainer.nestedContainer(keyedBy: CodingKeys.User.RealInfo.self, forKey: .realInfo) | |
self.fullName = try realInfoContainer.decode(String.self, forKey: .fullName) | |
// container for [{ "count": 4 }, { "count": 5 }] | |
var reviewCountContainer = try container.nestedUnkeyedContainer(forKey: .reviewsCount) | |
if let count = reviewCountContainer.count { | |
self.reviewCounts.reserveCapacity(count) | |
} | |
while !reviewCountContainer.isAtEnd { | |
let nestedReviewCountContainer = try reviewCountContainer.nestedContainer(keyedBy: CodingKeys.ReviewsCount.self) | |
self.reviewCounts.append(try nestedReviewCountContainer.decode(Int.self, forKey: .count)) | |
} | |
} | |
} | |
let jsonData = """ | |
{ | |
"id": 1, | |
"user": { | |
"user_name": "Tester", | |
"real_info": { | |
"full_name":"Jon Doe" | |
} | |
}, | |
"reviews_count": [ | |
{ | |
"count": 4 | |
}, | |
{ | |
"count": 5 | |
} | |
] | |
} | |
""".data(using: .utf8)! | |
do { | |
let response = try JSONDecoder().decode(ServerResponse.self, from: jsonData) | |
print(response) | |
} catch { | |
print(error) | |
} | |
// ServerResponse(id: 1, username: "Tester", fullName: "Jon Doe", reviewCounts: [4, 5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment