11.4. 'Must Do's While Decoding JSON adopting Codable
Let's look into the example JSON response for the details endpoint again:
{
"email": "[email protected]",
"name": "Alice Smith",
"phone": 6781234567
}And the data model for the above JSON that adopts the Codable protocol is:
struct Contact: Codable{
var name:String
var email:String
var phone:Int
}So let's compare the two and think about what are the things we need to handle to parse data carefully from JSON response by adopting Codable:
The names of the keys (e.g., "email") must match the names of the variables in the Codable struct (e.g., name).
The types of the values in the response JSON must match the types of the variables in the Codable struct. For example,
"phone": 6781234567means the value for the key "phone" has a value of integer data type. So we must set the type of the variablephonein structContacttoInt.You do not have to define variables for all the keys in JSON. You can selectively write variables to parse the needed data from a big JSON object.
So, the name and the data type of the variables in a Codable must match the name of the keys and the type of the values in JSON. Otherwise, JSON decoding will not work.
Last updated
Was this helpful?