Skip to content

Instantly share code, notes, and snippets.

@stleamist
Created November 27, 2019 05:36
Show Gist options
  • Save stleamist/a619b06a20978c8c24f034439b2121be to your computer and use it in GitHub Desktop.
Save stleamist/a619b06a20978c8c24f034439b2121be to your computer and use it in GitHub Desktop.
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