Created
May 8, 2023 21:43
-
-
Save boraseoksoon/7c6544969426ccb80ca99e3cc5e59a03 to your computer and use it in GitHub Desktop.
Swift json encode/decode using NSJSONSerialization
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 JSONConvertible { | |
func toJSONString() -> String? { | |
return (try? JSONSerialization.data(withJSONObject: toDictionary(), options: [])) | |
.flatMap { String(data: $0, encoding: .utf8) } | |
} | |
static func fromJSONString(_ jsonString: String) -> Self? { | |
return (try? JSONSerialization.jsonObject(with: Data(jsonString.utf8), options: [])) | |
.flatMap { $0 as? [String: Any] } | |
.flatMap { instance in | |
let newInstance = self.init() | |
newInstance.populate(using: instance) | |
return newInstance | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment