简体   繁体   中英

What's the difference between using JSONSerialization and JSONDecoder in swift?

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

Use JSONDecoder !

If I remember well, JSONDecoder appeared in Xcode 9, with Swift4. It's cleaner and much more efficient to encode and decode JSON. To do so, your Swift Class has to conform to Decodable Protocol.

JSON Serialization is the Old School. (Like Objective-C)

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.

In recent years, JSON has become the most widely used format to transfer data all over the internet. In the world of iOS development, it's very common for the developer to work with JSON data in Swift and use it for building iOS apps. There are some cool libraries like SwiftyJSON already available to work with JSON data in Swift and those libraries become popular because developers don't need to deal with unreadable mess with JSONSerialization to parse JSON. Fortunately, Swift 4 has introduced amazing Codable protocol as part of the Foundation framework and JSON parsing became a single or couple of lines of code. This is a fully supported solution by Apple that can be easily adopted. It provides customization to encode and decode complex scenarios with pain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM