Skip to content

Instantly share code, notes, and snippets.

@webuilder240
Created January 18, 2021 14:39
Show Gist options
  • Save webuilder240/c35b2adbab9d353a6e500db57b6e5b4c to your computer and use it in GitHub Desktop.
Save webuilder240/c35b2adbab9d353a6e500db57b6e5b4c to your computer and use it in GitHub Desktop.
Codableの練習。
import UIKit
import Foundation
var str = "Hello, playground"
struct Author: Codable {
var id: Int?
var name: String
var nickname: String?
}
struct Content: Codable {
var id: Int?
var title: String
var author: Author
var category: Category?
}
struct ContentsResponse: Codable {
var contents: [Content]
var isLastPage: Bool
}
struct Category: Codable {
var id: Int?
var name: String
}
let data = """
{
"contents": [
{
"id": 1,
"title": "title",
"author": {
"id": 1,
"name": "山田",
"nickname": "ドカベン"
},
},
{
"id": 2,
"title": "title-2",
"author": {
"id": 1,
"name": "山田",
"nickname": "ドカベン"
},
"category" : {
"id": 1,
"name": "カテゴリー"
}
},
],
"is_last_page": false
}
""".data(using: .utf8)!
let jsonDecoder = JSONDecoder()
jsonDecoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let contentsResponse = try jsonDecoder.decode(ContentsResponse.self, from: data)
contentsResponse.contents[1].category!.name
contentsResponse.isLastPage
} catch {
print(error.localizedDescription)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment