Skip to content

Instantly share code, notes, and snippets.

@trilliwon
Created December 23, 2018 13:18
Show Gist options
  • Save trilliwon/75915e96af9e6e4e06153cc8dec618ac to your computer and use it in GitHub Desktop.
Save trilliwon/75915e96af9e6e4e06153cc8dec618ac to your computer and use it in GitHub Desktop.
Codable Swift
struct Coordinate: Codable {
var latitude: Double
var longitude: Double
}
struct Landmark: Codable {
var name: String
var foundingYear: Int
var location: Coordinate
var vantagePoints: [Coordinate]
enum CodingKeys: String, CodingKey {
case name
case foundingYear = "founding_date"
case location
case vantagePoints = "vantage_points"
}
}
let landmarkJson = """
{
"name": "Yosemite National Park",
"founding_date": 1890,
"location": {
"longitude": 37.74896,
"latitude": -119.58851
},
"vantage_points": [
{
"longitude": 38.18491,
"latitude": -119.88604
},
{
"longitude": 37.49379,
"latitude": -119.19545
}
]
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(Landmark.self, from: landmarkJson)
print(product)
let encoder = JSONEncoder()
let r = try encoder.encode(product)
print(String(data: r, encoding: .utf8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment