Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ProductsDescription: Decodable {
- var data: [Product]
- enum CodingKeys: String, CodingKey {
- case data
- case products
- }
- enum ProductsKeys: String, CodingKey {
- case products
- }
- required init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- if let multiple = try? container.decode([Product].self, forKey: .data) {
- self.data = multiple
- } else {
- let nestedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
- let subvalues = try nestedContainer.decode([Product].self, forKey: .products)
- self.data = subvalues
- }
- }
- }
- struct Product: Codable {
- let options: [Option]
- struct Option: Codable {
- let value: String
- let key: Int
- }
- }
- let jsonMultiple = """
- {"data":[{"options":[{"value":"MULTIPLE","key":111}]}]}
- """
- let jsonSingle = """
- {"data":{"products":[{"options":[{"value":"SINGLE","key":333}]}]}}
- """
- func tryWith(json: String) {
- let data = json.data(using: .utf8)!
- let dataObj = try! JSONSerialization.jsonObject(with: data, options: [])
- let printedData = try! JSONSerialization.data(withJSONObject: dataObj, options: .prettyPrinted)
- let toPrint = String(data: printedData, encoding: .utf8)!
- print(toPrint)
- do {
- let products = try JSONDecoder().decode(ProductsDescription.self, from: data)
- print(products)
- products.data.forEach{ print($0) }
- } catch {
- print("Error: \(error)")
- }
- }
- print("-----")
- tryWith(json: jsonMultiple)
- print("-----")
- tryWith(json: jsonSingle)
- print("-----")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement