Flipturn Technical Flashcards
Steps to read json from file?
- add file.json to directory
- create Codable struct for said data
- read data
- decode data
How do you read a local json file?
let url = Bundle.main.url(forResource: “name”, withExtension: “json”)
How do you get the data from a url?
let data = Data(contentsOf: url)
How would you create Codable structs for this json?
{
“company”: {
“name”: “ABC Corp”,
“location”: “New York”
}
}
Create a “Model” type at the top level. and the model type has a “company” property, and the company type has a “name” property
What is the line to decode some json?
let model = decoder.decode(Model.self, from: data)
List 2 ways to decode snake case json
use coding keys or tell the decoder to expect snake case
How do you decode snake case with coding keys?
the codable struct needs an enum that conforms to CodingKey
Decode this json:
{
“company”: {
“legal_name”: “ABC Corp”,
“location”: “New York”
}
}
Create a “Model” type, then create a “Company” type. And Company should have an enum that conforms to “CodingKey”
Steps to read json from string
same as from file except the Data initializer uses string.utf8, ie:
let data = Data(string.utf8)