Skip to content

Instantly share code, notes, and snippets.

@hamishknight
Last active June 14, 2017 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamishknight/9b5c202fe6d8289ee2cb9403876a1b41 to your computer and use it in GitHub Desktop.
Save hamishknight/9b5c202fe6d8289ee2cb9403876a1b41 to your computer and use it in GitHub Desktop.
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