Junior — Middle
How do you handle JSON data and convert it into a processing-friendly structure?
sobes.tech AI
Answer from AI
In iOS, protocols Codable (Decodable and Encodable) are commonly used for working with JSON data. First, a structure or class that matches the JSON structure is created and marked as Codable. Then, JSONDecoder is used to convert JSON into a Swift object, making it easy to work with data.
Example:
struct User: Codable {
let id: Int
let name: String
let email: String
}
let jsonData = ... // data in JSON format
let decoder = JSONDecoder()
do {
let user = try decoder.decode(User.self, from: jsonData)
print(user.name)
} catch {
print("Error parsing JSON: \(error)")
}
This approach ensures type safety and ease of working with data.