Created
April 22, 2021 18:40
-
-
Save alekseylichtman/8029332b7f2e923dfdefcecc380a60f4 to your computer and use it in GitHub Desktop.
Swift. Convert any object into JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol JSONConvertible: Codable { | |
func convertToJson() -> String | |
} | |
extension JSONConvertible { | |
func convertToJson() -> String { | |
let jsonEncoder = JSONEncoder() | |
let jsonData = try! jsonEncoder.encode(self) | |
let json = String(data: jsonData, encoding: String.Encoding.utf8) | |
return json! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Convert any object into JSON
Inherit your structure from JSONConvertible.
Call method convertToJson() on your object to get the JSON.