Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Created October 26, 2022 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/3c2ed90cde51909f2eb3d286a5292d06 to your computer and use it in GitHub Desktop.
Save cecilemuller/3c2ed90cde51909f2eb3d286a5292d06 to your computer and use it in GitHub Desktop.
Swift: JSON helpers
import Foundation
class JSON {
static func encodeData<T>(_ from: T, format: JSONEncoder.OutputFormatting = .sortedKeys) -> Data? where T: Encodable {
let encoder = JSONEncoder()
encoder.outputFormatting = format
do {
return try encoder.encode(from)
} catch {
print(error)
return nil
}
}
static func encodeString<T>(_ from: T, format: JSONEncoder.OutputFormatting = .sortedKeys) -> String? where T: Encodable {
if let data = encodeData(from, format: format), let text = String(data: data, encoding: .utf8) {
return text
}
return nil
}
static func decodeData<T>(_ data: Data, to: T.Type) -> T? where T: Decodable {
do {
let decoder = JSONDecoder()
return try decoder.decode(to, from: data)
} catch {
print(error)
return nil
}
}
static func decodeString<T>(_ text: String, to: T.Type) -> T? where T: Decodable {
if let data = text.data(using: .utf8) {
return decodeData(data, to: to)
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment