Handling JSON in Swift
Introduction to JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Swift, handling JSON is essential for interacting with web services and APIs.
Parsing JSON in Swift
Swift provides a built-in way to parse JSON using the JSONDecoder class. To parse JSON, you first need a model that conforms to the Codable protocol.
Example JSON:
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com"
}
Here’s how you can create a model in Swift:
struct User: Codable {
let name: String
let age: Int
let email: String
}
Now, you can decode this JSON data into a User object:
let jsonData = """
{
"name": "John Doe",
"age": 30,
"email": "john.doe@example.com"
}
""".data(using: .utf8)!
do {
let user = try JSONDecoder().decode(User.self, from: jsonData)
print(user)
} catch {
print("Error decoding JSON: \(error)")
}
Encoding JSON in Swift
To convert a Swift object back into JSON, you can use the JSONEncoder class. This is useful when you need to send data to a server.
Using the User model defined earlier, here’s how you can encode it:
let user = User(name: "Jane Doe", age: 25, email: "jane.doe@example.com")
do {
let jsonData = try JSONEncoder().encode(user)
if let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
} catch {
print("Error encoding JSON: \(error)")
}
This will output a JSON string representation of the User object.
Handling JSON Errors
When working with JSON, it's important to handle errors that may occur during parsing or encoding. The do-catch statement in Swift allows you to catch errors gracefully and respond accordingly.
For example:
do {
let user = try JSONDecoder().decode(User.self, from: jsonData)
// Use user object
} catch let decodingError as DecodingError {
switch decodingError {
case .dataCorrupted(let context):
print("Data corrupted: \(context)")
case .keyNotFound(let key, let context):
print("Key '\(key)' not found: \(context)")
case .typeMismatch(let type, let context):
print("Type '\(type)' mismatch: \(context)")
case .valueNotFound(let value, let context):
print("Value '\(value)' not found: \(context)")
default:
print("Decoding error: \(decodingError)")
}
} catch {
print("Unknown error: \(error)")
}
Conclusion
Handling JSON in Swift is straightforward with the use of the Codable protocol, JSONDecoder, and JSONEncoder. By understanding how to parse and encode JSON, you can effectively work with web services and APIs in your applications.
