Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. import Foundation
  2.  
  3. let payload1 = """
  4.  
  5. {
  6. "coordinates": [
  7. {
  8. "latitude": 37.332,
  9. "longitude": -122.011
  10. }
  11. ]
  12. }
  13.  
  14. """.data(using: .utf8)!
  15.  
  16. let payload2 = """
  17.  
  18. {
  19. "coordinates": [
  20. [37.332,-122.011]
  21. ]
  22. }
  23.  
  24. """.data(using: .utf8)!
  25.  
  26. let payload3 = """
  27.  
  28. {
  29. "coordinates": [
  30. "37.332,-122.011"
  31. ]
  32. }
  33.  
  34. """.data(using: .utf8)!
  35.  
  36. struct Place: Codable {
  37.  
  38. let latitude: Double
  39. let longitude: Double
  40.  
  41. private enum CodingKeys: String, CodingKey {
  42. case latitude
  43. case longitude
  44. }
  45.  
  46. init(from decoder: Decoder) throws {
  47.  
  48. if let container = try? decoder.container(keyedBy: CodingKeys.self) {
  49. self.latitude = try container.decode(Double.self, forKey: .latitude)
  50. self.longitude = try container.decode(Double.self, forKey: .longitude)
  51. }
  52. else if var container = try? decoder.unkeyedContainer() {
  53. self.latitude = try container.decode(Double.self)
  54. self.longitude = try container.decode(Double.self)
  55. }
  56. else if let container = try? decoder.singleValueContainer() {
  57. let value = try container.decode(String.self)
  58. let values = value.components(separatedBy: ",")
  59.  
  60. guard values.count == 2,
  61. let latiude = Double(values[0]),
  62. let longitude = Double(values[1]) else {
  63. throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unable to decode coordinate")
  64. }
  65.  
  66. self.latitude = latiude
  67. self.longitude = longitude
  68. }
  69. else {
  70. let context = DecodingError.Context.init(codingPath: decoder.codingPath, debugDescription: "Unable to decode!")
  71. throw DecodingError.dataCorrupted(context)
  72. }
  73. }
  74. }
  75.  
  76. if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload1) {
  77. print("Payload1: \(payload1Dict)")
  78. }
  79.  
  80. if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload2) {
  81. print("Payload2: \(payload1Dict)")
  82. }
  83.  
  84. if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload3) {
  85. print("Payload1: \(payload1Dict)")
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement