Created
November 27, 2019 05:36
-
-
Save stleamist/a619b06a20978c8c24f034439b2121be to your computer and use it in GitHub Desktop.
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
import Foundation | |
public extension Encodable { | |
func jsonString(options: JSONEncoder.OutputFormatting = .prettyPrinted) -> String? { | |
let encoder = JSONEncoder() | |
encoder.outputFormatting = options | |
guard let jsonStringData = try? encoder.encode(self) else { | |
return nil | |
} | |
return String(data: jsonStringData, encoding: .utf8) | |
} | |
} | |
public extension Decodable { | |
init?(jsonString: String) { | |
guard let jsonStringData = jsonString.data(using: .utf8) else { | |
return nil | |
} | |
guard let decoded = try? JSONDecoder().decode(Self.self, from: jsonStringData) else { | |
return nil | |
} | |
self = decoded | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment