Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Paste this in a Swift Playground
- */
- import Foundation
- import CoreLocation
- var json = """
- {
- "name" : "Test",
- "latitude" : 39.9638412115116,
- "longitude" : 4.27464941734696
- }
- """.data(using: .utf8)!
- struct MyLocation: Codable {
- let name: String
- let latitude: Double
- let longitude: Double
- let location: CLLocationCoordinate2D
- enum CodingKeys: String, CodingKey {
- case name
- case latitude
- case longitude
- }
- public init(from decoder: Decoder) throws {
- let container = try decoder.container(keyedBy: CodingKeys.self)
- name = try container.decode(String.self, forKey: .name)
- latitude = try container.decode(Double.self, forKey: .latitude)
- longitude = try container.decode(Double.self, forKey: .longitude)
- location = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
- }
- func encode(to encoder: Encoder) throws {
- var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(name, forKey: .name)
- try container.encode(latitude, forKey: .latitude)
- try container.encode(longitude, forKey: .longitude)
- }
- }
- let myLocation = try JSONDecoder().decode(MyLocation.self, from: json)
- print(myLocation)
- let encodedMyLocation = try JSONEncoder().encode(myLocation)
- print(encodedMyLocation)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement