Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created May 8, 2023 21:43
Show Gist options
  • Save boraseoksoon/7c6544969426ccb80ca99e3cc5e59a03 to your computer and use it in GitHub Desktop.
Save boraseoksoon/7c6544969426ccb80ca99e3cc5e59a03 to your computer and use it in GitHub Desktop.
Swift json encode/decode using NSJSONSerialization
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