In Swift, you can easily decode and encode JSON using the Codable
protocol. This protocol is a type alias for the Encodable
and Decodable
protocols, enabling types to be encoded to and decoded from JSON effortlessly.
To encode a Swift object to JSON, you simply create an instance of JSONEncoder
and call the encode
method.
Similarly, to decode JSON into a Swift object, you create an instance of JSONDecoder
and call the decode
method.
// Example Swift struct conforming to Codable
struct User: Codable {
var id: Int
var name: String
}
// Encoding a User instance to JSON
let user = User(id: 1, name: "John Doe")
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(user) {
let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString) // {"id":1,"name":"John Doe"}
}
// Decoding JSON back to a User instance
let json = "{\"id\":1,\"name\":\"John Doe\"}"
let decoder = JSONDecoder()
if let jsonData = json.data(using: .utf8) {
if let decodedUser = try? decoder.decode(User.self, from: jsonData) {
print(decodedUser.name) // John Doe
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?