Want to serialize or convert Swift objects to JSON? In Swift 4, you can inherit from the Codable type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | struct Dog: Codable { var name: String var owner: String } // Encode let dog = Dog(name: "Rex", owner: "Etgar") let jsonEncoder = JSONEncoder() let jsonData = try jsonEncoder.encode(dog) let json = String(data: jsonData, encoding: String.Encoding.utf16) // Decode let jsonDecoder = JSONDecoder() let secondDog = try jsonDecoder.decode(Dog.self, from: jsonData) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.