Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- let payload1 = """
- {
- "coordinates": [
- {
- "latitude": 37.332,
- "longitude": -122.011
- }
- ]
- }
- """.data(using: .utf8)!
- let payload2 = """
- {
- "coordinates": [
- [37.332,-122.011]
- ]
- }
- """.data(using: .utf8)!
- let payload3 = """
- {
- "coordinates": [
- "37.332,-122.011"
- ]
- }
- """.data(using: .utf8)!
- struct Place: Codable {
- let latitude: Double
- let longitude: Double
- private enum CodingKeys: String, CodingKey {
- case latitude
- case longitude
- }
- init(from decoder: Decoder) throws {
- if let container = try? decoder.container(keyedBy: CodingKeys.self) {
- self.latitude = try container.decode(Double.self, forKey: .latitude)
- self.longitude = try container.decode(Double.self, forKey: .longitude)
- }
- else if var container = try? decoder.unkeyedContainer() {
- self.latitude = try container.decode(Double.self)
- self.longitude = try container.decode(Double.self)
- }
- else if let container = try? decoder.singleValueContainer() {
- let value = try container.decode(String.self)
- let values = value.components(separatedBy: ",")
- guard values.count == 2,
- let latiude = Double(values[0]),
- let longitude = Double(values[1]) else {
- throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unable to decode coordinate")
- }
- self.latitude = latiude
- self.longitude = longitude
- }
- else {
- let context = DecodingError.Context.init(codingPath: decoder.codingPath, debugDescription: "Unable to decode!")
- throw DecodingError.dataCorrupted(context)
- }
- }
- }
- if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload1) {
- print("Payload1: \(payload1Dict)")
- }
- if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload2) {
- print("Payload2: \(payload1Dict)")
- }
- if let payload1Dict = try? JSONDecoder().decode([String: [Place]].self, from: payload3) {
- print("Payload1: \(payload1Dict)")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement