Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic JSON serialization and deserialization of objects in Swift

I'm looking for a way to automatically serialize and deserialize class instances in Swift. Let's assume we have defined the following class …

class Person {     let firstName: String     let lastName: String      init(firstName: String, lastName: String) {         self.firstName = firstName         self.lastName = lastName     } } 

… and Person instance:

let person = Person(firstName: "John", lastName: "Doe") 

The JSON representation of person would be the following:

{     "firstName": "John",     "lastName": "Doe" } 

Now, here are my questions:

  1. How can I serialize the person instance and get the above JSON without having to manually add all properties of the class to a dictionary which gets turned into JSON?
  2. How can I deserialize the above JSON and get back an instantiated object that is statically typed to be of type Person? Again, I don't want to map the properties manually.

Here's how you'd do that in C# using Json.NET:

var person = new Person("John", "Doe"); string json = JsonConvert.SerializeObject(person); // {"firstName":"John","lastName":"Doe"}  Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json); 
like image 462
Marius Schulz Avatar asked Nov 08 '14 18:11

Marius Schulz


People also ask

What is JSON serialization in Swift?

Swift version: 5.6. If you want to parse JSON by hand rather than using Codable , iOS has a built-in alternative called JSONSerialization and it can convert a JSON string into a collection of dictionaries, arrays, strings and numbers in just a few lines of code.

What is serialization and deserialization in Swift?

2019. Serialization is a process of converting your instances to another representation, like a string or a stream of bytes. The reverse process of turning the data into an instance is called decoding, or deserialization.

What is JSON serialization and deserialization?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).


1 Answers

As shown in WWDC2017 @ 24:48 (Swift 4), we will be able to use the Codable protocol. Example

public struct Person : Codable {    public let firstName:String    public let lastName:String    public let location:Location } 

To serialize

let payload: Data = try JSONEncoder().encode(person) 

To deserialize

let anotherPerson = try JSONDecoder().decode(Person.self, from: payload) 

Note that all properties must conform to the Codable protocol.

An alternative can be JSONCodable which is used by Swagger's code generator.

like image 100
Alex Nolasco Avatar answered Sep 19 '22 15:09

Alex Nolasco