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:
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?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);
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With