Created
January 2, 2021 17:39
-
-
Save donnywals/f2964530574672ac1c2a63ab4caac708 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let json = """ | |
{ | |
"userId": 0, | |
"name": "Donny" | |
} | |
""".data(using: .utf8)! | |
struct User: Codable { | |
enum DecodingKeys: CodingKey { | |
case userId, name | |
} | |
enum EncodingKeys: String, CodingKey { | |
case userId = "user_id" | |
case name | |
} | |
let userId: Int | |
let name: String | |
init(from decoder: Decoder) throws { | |
let container = try decoder.container(keyedBy: DecodingKeys.self) | |
self.userId = try container.decode(Int.self, forKey: .userId) | |
self.name = try container.decode(String.self, forKey: .name) | |
} | |
func encode(to encoder: Encoder) throws { | |
var container = encoder.container(keyedBy: EncodingKeys.self) | |
try container.encode(userId, forKey: .userId) | |
try container.encode(name, forKey: .name) | |
} | |
} | |
let decoder = JSONDecoder() | |
let encoder = JSONEncoder() | |
let user = try! decoder.decode(User.self, from: json) | |
let data = try! encoder.encode(user) | |
// prints "{\"user_id\":0,\"name\":\"Donny\"}" | |
print(String(data: data, encoding: .utf8)!) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment