Created
October 26, 2022 07:41
-
-
Save cecilemuller/3c2ed90cde51909f2eb3d286a5292d06 to your computer and use it in GitHub Desktop.
Swift: JSON helpers
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 | |
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