Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Playing with Codable
import UIKit
struct JSONBook: Codable {
let book: Book
}
// MARK: - Book
struct Book: Codable {
let isbn, language, binding, publisher: String
let dimensions: String
let image: String
let publishDate, title: String
let authors: [String]
let pages: Int
let subjects: [String]
let titleLong, edition, msrp, format: String
let isbn13, synopsys, datePublished: String
enum CodingKeys: String, CodingKey {
case isbn, language, binding, publisher, dimensions, image
case publishDate = "publish_date"
case title, authors, pages, subjects
case titleLong = "title_long"
case edition, msrp, format, isbn13, synopsys
case datePublished = "date_published"
}
}
let json = """
{ "book" : { "isbn" : "0596007124", "language" : "Eng English", "binding" : "Paperback", "publisher" : "O'reilly Media", "dimensions" : "xxxvi, 638 p. : ill.", "image" : "https://images.isbndb.com/covers/71/26/9780596007126.jpg", "publish_date" : "2004", "title" : "Head First Design Patterns: A Brain-friendly Guide", "authors" : [ "Eric Freeman", "Bert Bates", "Kathy Sierra", "Elisabeth Robson" ], "pages" : 694, "subjects" : [ "Computer software--Development", "Java (Computer program language)", "QA76.76.D47 H427 2004" ], "title_long" : "Head First Design Patterns: A Brain-friendly Guide", "edition" : "1", "msrp" : "69.99", "format" : "print", "isbn13" : "9780596007126", "synopsys" : "Welcome To Design Patterns -- Keeping Your Objects In The Know -- Decorating Objects -- Baking With Oo Goodness -- One Of A Kind Objects -- Encapsulating Invocation -- Being Adaptive -- Encapsulating Algorithms -- Well-managed Collections -- The State Of Things -- Controlling Object Access -- Patterns Of Patterns -- Patterns In The Real World -- Appendix: Leftover Patterns. Eric Freeman, Elisabeth Freeman, With Kathy Sierra And Burt Bates. Includes Index.", "date_published" : "2004" }}
"""
let jsonFail = "gotas"
let textDataOpenApi = json.data(using: .utf8)
let textDataISBN = json.data(using: .utf8)
var foundISBNBook: JSONBook?
var foundOpenApiBook: JSONBook?
if let textData = textDataOpenApi {
foundOpenApiBook = try? JSONDecoder().decode(JSONBook.self, from: textData)
}
if let textData = textDataISBN {
foundISBNBook = try? JSONDecoder().decode(JSONBook.self, from: textData)
}
if foundISBNBook != nil {
print("ISBN IS THE WINNER")
} else if foundOpenApiBook != nil {
print("Open is runner up")
} else {
print("no books")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment