Created
March 3, 2020 18:34
-
-
Save foxicode/bc4054fd46deb4a92b3258f3391c3ecf to your computer and use it in GitHub Desktop.
Swift extensions for converting dictionaries and arrays to json strings and back
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 | |
extension Data { | |
init?(json: Any) { | |
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .fragmentsAllowed) else { return nil } | |
self.init(data) | |
} | |
func jsonToDictionary() -> [String: Any]? { | |
(try? JSONSerialization.jsonObject(with: self, options: .allowFragments)) as? [String: Any] | |
} | |
func jsonToArray() -> [Any]? { | |
(try? JSONSerialization.jsonObject(with: self, options: .allowFragments)) as? [Any] | |
} | |
} |
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 | |
extension String { | |
init?(json: Any) { | |
guard let data = Data(json: json) else { return nil } | |
self.init(decoding: data, as: UTF8.self) | |
} | |
func jsonToDictionary() -> [String: Any]? { | |
self.data(using: .utf8)?.jsonToDictionary() | |
} | |
func jsonToArray() -> [Any]? { | |
self.data(using: .utf8)?.jsonToArray() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment