Member-only story
JSON parsing
3 min readDec 6, 2024
- How do you decode data in iOS? JSONDecoder/JsonSerialization
- What is codable?
- How to decode data with custom properties?
- How can we decode date to date property?
- What is convertFromSnakeCase?
- How can we decode using custom decoder?
- How to decode same properties with different data type?
1. How do you decode data in iOS? JSONDecoder/JSONSerialization
Explanation:
In iOS, decoding data (e.g., JSON) involves converting the data into a usable Swift model or dictionary. There are two primary approaches:
- JSONDecoder:
- Used to decode JSON data into strongly-typed Swift objects.
- Works with Swift’s
Codable
protocol. - Provides type safety and avoids runtime type errors.
Example:
struct User: Codable {
let id: Int
let name: String
}
let jsonData = """
{
"id": 1,
"name": "Niraj"
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: jsonData)
print(user.name) // Output: Niraj
2. What is Codable
?
Explanation:
Codable
is a protocol that combines Encodable
and Decodable
. It allows Swift types to easily encode and decode data formats like JSON…