What's the difference between using JSONSerialization and JSONDecoder in swift, while converting JSON to a swift model? It's seems like they are doing the same job. If they do, then when is which to use? Thank you in advance
Apple has provided JSONDecoder which is a huge relief in swift4 and onwards. We can decode json in just one line. eg
{// sample from quicktype app online
"greeting": "Welcome to quicktype!",
"instructions": [
"Type or paste JSON here",
"Or choose a sample above",
"quicktype will generate code in your",
"chosen language to parse the sample data"
]
}
// MARK: - Welcome
struct Welcome: Codable {
let greeting: String
let instructions: [String]
}
// let welcome = try? newJSONDecoder().decode(Welcome.self, from: jsonData)
Here welcome is the struct which is conforming to codable protocol.
If you want to parse JSON by hand rather than using Codable, iOS has a built-in alternative called JSONSerialization.But i think everybody would like to use JSONDecoder. And also quicktype creates json model classes or struct for u for free. Check yourself.