Skip to content

Instantly share code, notes, and snippets.

@Andy0570
Created November 18, 2020 03:20
Show Gist options
  • Save Andy0570/5669b5195b2c5b2da13cbc6be3daa01b to your computer and use it in GitHub Desktop.
Save Andy0570/5669b5195b2c5b2da13cbc6be3daa01b to your computer and use it in GitHub Desktop.
JSON 字符串解析
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()
}
}
@Andy0570
Copy link
Author

Usage:

 let dict: [String: Any] = [
   "name": "John",
   "surname": "Doe",
   "age": 31
 ]
 print(dict)
 // ["surname": "Doe", "name": "John", "age": 31]
 let json = String(json: dict)
 print(json)
 // Optional("{\"surname\":\"Doe\",\"name\":\"John\",\"age\":31}")

 let restoredDict = json?.jsonToDictionary()
 print(restoredDict)
 // Optional(["name": John, "surname": Doe, "age": 31])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment