Advertisement
Larme

Untitled

Jun 17th, 2020
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.74 KB | None | 0 0
  1.  
  2. class ProductsDescription: Decodable {
  3.     var data: [Product]
  4.    
  5.     enum CodingKeys: String, CodingKey {
  6.         case data
  7.         case products
  8.     }
  9.     enum ProductsKeys: String, CodingKey {
  10.         case products
  11.     }
  12.    
  13.    
  14.     required init(from decoder: Decoder) throws {
  15.         let container = try decoder.container(keyedBy: CodingKeys.self)
  16.         if let multiple = try? container.decode([Product].self, forKey: .data) {
  17.             self.data = multiple
  18.         } else {
  19.             let nestedContainer = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .data)
  20.             let subvalues = try nestedContainer.decode([Product].self, forKey: .products)
  21.             self.data = subvalues
  22.         }
  23.     }
  24. }
  25.  
  26. struct Product: Codable {
  27.     let options: [Option]
  28.    
  29.     struct Option: Codable {
  30.         let value: String
  31.         let key: Int
  32.     }
  33. }
  34.  
  35.  
  36. let jsonMultiple = """
  37. {"data":[{"options":[{"value":"MULTIPLE","key":111}]}]}
  38. """
  39. let jsonSingle = """
  40. {"data":{"products":[{"options":[{"value":"SINGLE","key":333}]}]}}
  41. """
  42.  
  43.  
  44.  
  45. func tryWith(json: String) {
  46.    
  47.     let data = json.data(using: .utf8)!
  48.     let dataObj = try! JSONSerialization.jsonObject(with: data, options: [])
  49.     let printedData = try! JSONSerialization.data(withJSONObject: dataObj, options: .prettyPrinted)
  50.     let toPrint = String(data: printedData, encoding: .utf8)!
  51.     print(toPrint)
  52.     do {
  53.         let products = try JSONDecoder().decode(ProductsDescription.self, from: data)
  54.         print(products)
  55.        
  56.         products.data.forEach{ print($0) }
  57.     } catch {
  58.         print("Error: \(error)")
  59.     }
  60. }
  61.  
  62. print("-----")
  63. tryWith(json: jsonMultiple)
  64. print("-----")
  65. tryWith(json: jsonSingle)
  66. print("-----")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement