Created
February 14, 2020 04:37
-
-
Save raditsan/1c3c24758a8372615665a310c9e58508 to your computer and use it in GitHub Desktop.
Decode from struct or class model to JSON String or Data
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 UIKit | |
func newJSONDecoder() -> JSONDecoder { | |
let decoder = JSONDecoder() | |
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { | |
decoder.dateDecodingStrategy = .iso8601 | |
} | |
return decoder | |
} | |
func newJSONEncoder() -> JSONEncoder { | |
let encoder = JSONEncoder() | |
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { | |
encoder.dateEncodingStrategy = .iso8601 | |
} | |
return encoder | |
} |
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 UIKit | |
struct ExampleStructOrClass: Codable { | |
var name: String | |
var address: String | |
var age: Int | |
var isSingle: Bool | |
var favourite: [String] | |
init(name: String, address: String, age: Int, isSingle: Bool, favourite: [String]) { | |
self.name = name | |
self.address = address | |
self.age = age | |
self.isSingle = isSingle | |
self.favourite = favourite | |
} | |
func jsonData() throws -> Data { | |
return try newJSONEncoder().encode(self) | |
} | |
func jsonString(encoding: String.Encoding = .utf8) throws -> String? { | |
return String(data: try self.jsonData(), encoding: encoding) | |
} | |
} |
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
var data = ExampleStructOrClass(name: "Raditsan", address: "Indonesia", age: 26, isSingle: false, favourite: ["Game","Coding","Reading"]) | |
do { | |
print("jsonString \(try data.jsonString() ?? "")") | |
} catch let error { | |
print(error.localizedDescription) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output
jsonString {"age":26,"isSingle":false,"favourite":["Game","Coding","Reading"],"name":"Raditsan","address":"Indonesia"}