Guest User

Untitled

a guest
Nov 13th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. @IBAction func testing(_ sender: Any) {
  2. let url = URL(string: "http://example.com/cars/mustang")
  3.  
  4. let task = URLSession.shared.dataTask(with: url!) { data, response, error in
  5. guard error == nil else {
  6. print(error!)
  7. return
  8. }
  9. guard let data = data else {
  10. print("Data is empty")
  11. return
  12. }
  13. let json = try! JSONSerialization.jsonObject(with: data, options: [])
  14. print(json)
  15. }
  16. task.resume()
  17. }
  18.  
  19. (
  20. {
  21. color = "red";
  22. engine = "5.0";
  23. }
  24. )
  25.  
  26. let json = try! JSONSerialization.jsonObject(with: data, options: [])
  27.  
  28. guard let jsonArray = json as? [[String: String]] else {
  29. return
  30. }
  31. let carColor = jsonArray[0]["color"]
  32. print(carColor!) // output: red
  33.  
  34. class CarInfo: Decodable
  35.  
  36. var color: String
  37.  
  38. var engine: String
  39.  
  40. enum CarInfoCodingKey: String, CodingKey {
  41. case color
  42. case engine
  43. }
  44.  
  45. required init(from decoder: Decoder) throws
  46.  
  47. class CarInfo: Decodable {
  48. var color: String
  49. var engine: String
  50. enum CarInfoCodingKey: String, CodingKey {
  51. case color
  52. case engine
  53. }
  54. public init(from decoder: Decodabler) throws {
  55. let container = try decoder.container(keyedBy: CarInfoCodingKey.self)
  56. self.color = try container.decode(String.self, forKey: .color)
  57. self.engine = try contaire.decode(String.self, forKey: .engine)
  58. }
  59. }
  60.  
  61. let carinfo = try JsonDecoder().decode(CarInfo.self, from: jsonData)
Add Comment
Please, Sign In to add comment