Member-only story

JSON parsing

  1. How do you decode data in iOS? JSONDecoder/JsonSerialization
  2. What is codable?
  3. How to decode data with custom properties?
  4. How can we decode date to date property?
  5. What is convertFromSnakeCase?
  6. How can we decode using custom decoder?
  7. 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:

  1. 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…

--

--

No responses yet