an introduction:
In this topic, we will address one of the most important updates that Apple provided with the Xcode 9 and Swift4
Protocol Codable ? Which will replace the old and notorious NSCoding, make your Data Model Encodable, Decodable to fully integrate with any external data such as JSON
Now you can transfer data to and from JSON with one line?
Application:
Let's take an example of Structure with the name Movie, here I will define the Structure as Codable so that we can convert it to and from JSON easily.
struct Movie: Codable {
enum MovieGenere: String, Codable {
case horror, skifi, comedy, adventure, animation
}
var name : String
var moviesGenere : [MovieGenere]
var rating : Int
}
?
Let's create an object from this structure for clarity
for example:
In this example we have a comedy, adventure, and animation movie called Up with a rating of 8/10
Now let's see how to convert this object into JSON data
Encode
let jsonData = try? JSONEncoder().encode(upMovie)
let jsonString = String(data: jsonData, encoding: .utf8)
print("JSON String : " + jsonString!)
Voala
The () JSONEncoder will convert the object into JSON Data
And the result will be as follows
{ "name": "Up", moviesGenere: [ comedy, "adventure", "animation" ], "rating": 4 }
Decode
Likewise, we will use the JSONDecoder () to transfer data from JSON to Object from the Movie.
let upMovie = try? JSONDecoder().decode(Movie.self, from: jsonData)
print("Name : \(upMovie.name)")
print("Rating : \(upMovie.rating)")
By unzipping the JSON file, we will get the upMovie object, and we can access its features and use them as we wish.
The result will be as follows
Name: Up Rating: 4
Here we come to the conclusion of our topic
read also :
Comments
Post a Comment