generic swift object serialization? - swift

Is there a generic way to serialize/deserialize objects for iOS? I was using the following code, and the system functions I was calling were deprecated in iOS 12:
func object(forKey:String) -> Any? {
if let data = get(BLOB_COL, forKey) {
return NSKeyedUnarchiver.unarchiveObject(with: data as! Data)
}
return nil
}
func set(_ object:Any, forKey: String) {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
updateOrInsert(forKey, BLOB_COL, data)
}
It looks like the new versions of these functions requires knowledge of the object classes, and different signatures for unarchiving different collection types... is there a simple way to handle this generically?

If you would like to use NSKeyedArchiver/NSKeyedUnarchiver:
When archiving change:
NSKeyedArchiver.archivedData...
to
NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
And when unarchiving change
NSKeyedUnarchiver.unarchiveObject...
to
NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
Codable protocol generic approach
If you would like to use Codable to encode and decode (serialize) your Data you can extend Encodable protocol and create a method to encode any object that conforms to it:
extension Encodable {
func data(using encoder: JSONEncoder = JSONEncoder()) throws -> Data { try encoder.encode(self) }
}
And to decode the encoded data you can extend Data and create a generic method that decode any object that conforms to Decodable:
extension Data {
func object<T: Decodable>(using decoder: JSONDecoder = JSONDecoder()) throws -> T {
try decoder.decode(T.self, from: self)
}
// you can also create a string property to convert the JSON data to String
var string: String? { String(data: self, encoding: .utf8) }
}
Usage:
struct Person: Codable {
let name: String
let age: Int
}
do {
// encoding
let person = Person(name: "Joe", age: 10)
var people = [Person]()
people.append(person)
let data = try people.data()
print(data.string ?? "") // [{"name":"Joe","age":10}]
// decoding
let loadedPeople: [Person] = try data.object()
loadedPeople.forEach({print( $0.name, $0.age)}) // Joe 10
} catch {
print(error)
}

As Leo says, stop using NSKeyedArchiver and use the Codable protocol. That's the modern, Swifty way to serialize/deserialize your objects.

Related

Swift Decodable - How to decode nested JSON that has been base64 encoded

I am attempting to decode a JSON response from a third-party API which contains nested/child JSON that has been base64 encoded.
Contrived Example JSON
{
"id": 1234,
"attributes": "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9",
}
PS "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9" is { 'name': 'some-value' } base64 encoded.
I have some code that is able to decode this at present but unfortunately I have to reinstanciate an additional JSONDecoder() inside of the init in order to do so, and this is not cool...
Contrived Example Code
struct Attributes: Decodable {
let name: String
}
struct Model: Decodable {
let id: Int64
let attributes: Attributes
private enum CodingKeys: String, CodingKey {
case id
case attributes
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int64.self, forKey: .id)
let encodedAttributesString = try container.decode(String.self, forKey: .attributes)
guard let attributesData = Data(base64Encoded: encodedAttributesString) else {
fatalError()
}
// HERE IS WHERE I NEED HELP
self.attributes = try JSONDecoder().decode(Attributes.self, from: attributesData)
}
}
Is there anyway to achieve the decoding without instanciating the additional JSONDecoder?
PS: I have no control over the response format and it cannot be changed.
If attributes contains only one key value pair this is the simple solution.
It decodes the base64 encoded string directly as Data – this is possible with the .base64 data decoding strategy – and deserializes it with traditional JSONSerialization. The value is assigned to a member name in the Model struct.
If the base64 encoded string cannot be decoded a DecodingError will be thrown
let jsonString = """
{
"id": 1234,
"attributes": "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9",
}
"""
struct Model: Decodable {
let id: Int64
let name: String
private enum CodingKeys: String, CodingKey {
case id, attributes
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int64.self, forKey: .id)
let attributeData = try container.decode(Data.self, forKey: .attributes)
guard let attributes = try JSONSerialization.jsonObject(with: attributeData) as? [String:String],
let attributeName = attributes["name"] else { throw DecodingError.dataCorruptedError(forKey: .attributes, in: container, debugDescription: "Attributes isn't eiter a dicionary or has no key name") }
self.name = attributeName
}
}
let data = Data(jsonString.utf8)
do {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
let result = try decoder.decode(Model.self, from: data)
print(result)
} catch {
print(error)
}
I find the question interesting, so here is a possible solution which would be to give the main decoder an additional one in its userInfo:
extension CodingUserInfoKey {
static let additionalDecoder = CodingUserInfoKey(rawValue: "AdditionalDecoder")!
}
var decoder = JSONDecoder()
let additionalDecoder = JSONDecoder() //here you can put the same one, you can add different options, same ones, etc.
decoder.userInfo = [CodingUserInfoKey.additionalDecoder: additionalDecoder]
Because the main method we use from JSONDecoder() is func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable and I wanted to keep it as such, I created a protocol:
protocol BasicDecoder {
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
}
extension JSONDecoder: BasicDecoder {}
And I made JSONDecoder respects it (and since it already does...)
Now, to play a little and check what could be done, I created a custom one, in the idea of having like you said a XML Decoder, it's basic, and it's just for the fun (ie: do no replicate this at home ^^):
struct CustomWithJSONSerialization: BasicDecoder {
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable {
guard let dict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { fatalError() }
return Attributes(name: dict["name"] as! String) as! T
}
}
So, init(from:):
guard let attributesData = Data(base64Encoded: encodedAttributesString) else { fatalError() }
guard let additionalDecoder = decoder.userInfo[.additionalDecoder] as? BasicDecoder else { fatalError() }
self.attributes = try additionalDecoder.decode(Attributes.self, from: attributesData)
Let's try it now!
var decoder = JSONDecoder()
let additionalDecoder = JSONDecoder()
decoder.userInfo = [CodingUserInfoKey.additionalDecoder: additionalDecoder]
var decoder2 = JSONDecoder()
let additionalDecoder2 = CustomWithJSONSerialization()
decoder2.userInfo = [CodingUserInfoKey.additionalDecoder: additionalDecoder]
let jsonStr = """
{
"id": 1234,
"attributes": "eyAibmFtZSI6ICJzb21lLXZhbHVlIiB9",
}
"""
let jsonData = jsonStr.data(using: .utf8)!
do {
let value = try decoder.decode(Model.self, from: jsonData)
print("1: \(value)")
let value2 = try decoder2.decode(Model.self, from: jsonData)
print("2: \(value2)")
}
catch {
print("Error: \(error)")
}
Output:
$> 1: Model(id: 1234, attributes: Quick.Attributes(name: "some-value"))
$> 2: Model(id: 1234, attributes: Quick.Attributes(name: "some-value"))
After reading this interesting post, I came up with a reusable solution.
You can create a new NestedJSONDecodable protocol which gets also the JSONDecoder in it's initializer:
protocol NestedJSONDecodable: Decodable {
init(from decoder: Decoder, using nestedDecoder: JSONDecoder) throws
}
Implement the decoder extraction technique (from the aforementioned post) together with a new decode(_:from:) function for decoding NestedJSONDecodable types:
protocol DecoderExtractable {
func decoder(for data: Data) throws -> Decoder
}
extension JSONDecoder: DecoderExtractable {
struct DecoderExtractor: Decodable {
let decoder: Decoder
init(from decoder: Decoder) throws {
self.decoder = decoder
}
}
func decoder(for data: Data) throws -> Decoder {
return try decode(DecoderExtractor.self, from: data).decoder
}
func decode<T: NestedJSONDecodable>(_ type: T.Type, from data: Data) throws -> T {
return try T(from: try decoder(for: data), using: self)
}
}
And change your Model struct to conform to NestedJSONDecodable protocol instead of Decodable:
struct Model: NestedJSONDecodable {
let id: Int64
let attributes: Attributes
private enum CodingKeys: String, CodingKey {
case id
case attributes
}
init(from decoder: Decoder, using nestedDecoder: JSONDecoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int64.self, forKey: .id)
let attributesData = try container.decode(Data.self, forKey: .attributes)
self.attributes = try nestedDecoder.decode(Attributes.self, from: attributesData)
}
}
The rest of your code will remain the same.
You could create a single decoder as a static property of Model, configure it once, and use it for all your Model decoding needs, both externally and internally.
Unsolicited thought:
Honestly, I would only recommend doing that if you're seeing a measurable loss of CPU time or crazy heap growth from the allocation of additional JSONDecoders… they're not heavyweight objects, less than 128 bytes unless there's some trickery I don't understand (which is pretty common though tbh):
let decoder = JSONDecoder()
malloc_size(Unmanaged.passRetained(decoder).toOpaque()) // 128

Is it possible to use a generic inside a generic struct init in Swift?

I would like to know if it is possible to use a generic type to initialize another generic. I put a example code below.
struct Object: Decodable {
let id: String?
let type: String?
}
struct JSON<T: Decodable>: Decodable {
let data: T?
}
func test<T: Decodable>(type: T.Type) {
let dataFromAPI = Data()
let model = JSONDecoder().decode(JSON<type>, from: dataFromAPI)
}
I am receiving this error message:
Use of undeclared type 'type'
If you want to call generic type struct then use this:
do {
let model = try JSONDecoder().decode(JSON<T>.self, from: dataFromAPI)
} catch let message {
print("JSON serialization error:" + "\(message)")
}
Or if you want to decode simple struct then:
do {
let model = try JSONDecoder().decode(Object.self, from: dataFromAPI)
} catch let message {
print("JSON serialization error:" + "\(message)")
}

How to encode Dictionary with JSONEncoder in Swift 4

I want to encode Dictionary to json with JSONEncoder.
It seems like a Request, receive a dictionary as parameter and encode it to json as http body.
The code is looks like this:
let dict = ["name": "abcde"]
protocol Request {
var params: [String: Encodable] { get set }
func encode<T>(_ value: T) throws -> Data where T : Encodable
}
extension Request {
func encode<T>(_ value: T) throws -> Data where T : Encodable {
return try JSONEncoder().encode(value)
}
var body: Data? {
if let encoded = try? self.encode(self.params) {
return encoded
}
return nil
}
}
struct BaseRequest: Request {
var params: [String : Encodable]
}
let req = BaseRequest(params: dict)
let body = req.body
But this code occurs error
Fatal error: Dictionary<String, Encodable> does not conform to Encodable because Encodable does not conform to itself. You must use a concrete type to encode or decode.
How could I make this encodable?
You have to introduce type erasure as follows:
struct AnyEncodable: Encodable {
let value: Encodable
init(value: Encodable) {
self.value = value
}
func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
struct Model: Encodable {
var params: [String: AnyEncodable]
}
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let json = try! encoder.encode(
Model(
params: [
"hello" : AnyEncodable.init(value: "world")
]
).params
)
print(String(data: json, encoding: .utf8))
If you want to define your struct as conforming to Codable, you can do it like this:
struct Model: Codable {
var param1: String
var param2: Int
}
let model = Model(param1: "test", param2: 0)
let encoded = try? JSONEncoder().encode(model)
let decoded = try? JSONDecoder().decode(Model.self, from: encoded!)
It won't really work if you set params: [String: Any] because the encoders/decoders don't know how to encode/decode Any, but they can do it for the primitive types.
If you want more help, you should read more about the new Codable protocol. I recommend this: https://hackernoon.com/everything-about-codable-in-swift-4-97d0e18a2999

Adding property observer to Decodable protocol in Swift 4

I am retrieving a URL from a JSON parse, and upon doing that I would like to convert that URL into a UIImage. Here is my current data struct:
struct Book: Decodable {
let author: String
let artworkURL: URL
let genres: [Genre]
let name: String
let releaseDate: String
}
I tried to do:
struct Book: Decodable {
let author: String
var bookArtwork: UIImage
let artworkURL: URL {
didSet {
do {
if let imageData: Data = try Data(contentsOf: artworkURL) {
bookArtwork = UIImage(data: imageData)!
}
} catch {
print(error)
}
}
let genres: [Genre]
let name: String
let releaseDate: String
}
But that does not conform to protocol 'Decodable'
Anyone else have a solution?
Below I will enumerate a few ways of handling this sort of scenario, but the right answer is that you simply should not be retrieving images during the parsing of the JSON. And you definitely shouldn't be doing this synchronously (which is what Data(contentsOf:) does).
Instead, you should should only retrieve the images as they're needed by the UI. And you want to retrieve images into something that can be purged in low memory scenarios, responding to the .UIApplicationDidReceiveMemoryWarning system notification. Bottom line, images can take a surprising amount of memory if you're not careful and you almost always want to decouple the images from the model objects themselves.
But, if you're absolutely determined to incorporate the image into the Book object (which, again, I'd advise against), you can either:
You can make the bookArtwork a lazy variable:
struct Book: Decodable {
let author: String
lazy var bookArtwork: UIImage = {
let data = try! Data(contentsOf: artworkURL)
return UIImage(data: data)!
}()
let artworkURL: URL
let genres: [Genre]
let name: String
let releaseDate: String
}
This is horrible pattern in this case (again, because we should never do synchronous network call), but it illustrates the idea of a lazy variable. You sometimes do this sort of pattern with computed properties, too.
Just as bad (for the same reason, that synchronous network calls are evil), you can also implement a custom init method:
struct Book: Decodable {
let author: String
let bookArtwork: UIImage
let artworkURL: URL
let genres: [Genre]
let name: String
let releaseDate: String
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
author = try values.decode(String.self, forKey: .author)
artworkURL = try values.decode(URL.self, forKey: .artworkURL)
genres = try values.decode([Genre].self, forKey: .genres)
name = try values.decode(String.self, forKey: .name)
releaseDate = try values.decode(String.self, forKey: .releaseDate)
// special processing for artworkURL
let data = try Data(contentsOf: artworkURL)
bookArtwork = UIImage(data: data)!
}
enum CodingKeys: String, CodingKey {
case author, artworkURL, genres, name, releaseDate
}
}
In fact, this is even worse than the prior pattern, because at least with the first option, the synchronous network calls are deferred until when you reference the UIImage property.
But for more information on this general pattern see Encode and Decode Manually in Encoding and Decoding Custom Types.
I provide these two above patterns, as examples of how you can have some property not part of the JSON, but initialized in some other manner. But because you are using Data(contentsOf:), neither of these are really advisable. But they're good patterns to be aware of in case the property in question didn't require some time consuming synchronous task, like you do here.
In this case, I think it's simplest to just provide a method to retrieve the image asynchronously when you need it:
Eliminate the synchronous network call altogether and just provide an asynchronous method to retrieve the image:
struct Book: Decodable {
let author: String
let artworkURL: URL
let genres: [Genre]
let name: String
let releaseDate: String
func retrieveImage(completionHandler: #escaping (UIImage?, Error?) -> Void) {
let task = URLSession.shared.dataTask(with: artworkURL) { data, _, error in
guard let data = data, error == nil else {
completionHandler(nil, error)
return
}
completionHandler(UIImage(data: data), nil)
}
task.resume()
}
}
Then, when you need the image for your UI, you can retrieve it lazily:
book.retrieveImage { image, error in
DispatchQueue.main.async { image, error in
cell.imageView.image = image
}
}
Those are a few approaches you can adopt.

Decodable Generic with Swift 4

I'm using the new Decodable protocol introduced in Swift 4.
Inside my unit test, I want to use a generic method that decodes a specific JSON file for a specific Decodable type.
I wrote the following function matching the JSONDecoder decode method:
var jsonDecoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}()
static let bundle: Bundle = {
let testBundle = Bundle(for: Decodable.self)
let sampleURL = testBundle.url(forResource: "api_samples", withExtension: "bundle")!
return Bundle(url: sampleURL)!
}()
static func getJSONSample(fileName: String) throws -> Data {
let url = Decodable.bundle.url(forResource: fileName, withExtension: "json")!
return try Data(contentsOf: url)
}
func assertDecode<Obj>(_ type: Obj.Type, fileName: String) where Obj: Decodable {
do {
let data = try Decodable.getJSONSample(fileName: fileName)
let _ = try jsonDecoder.decode(type, from: data)
// Same by using Obj.self, Obj.Type
} catch let error {
XCTFail("Should not have failed for \(type) with json \(fileName): \(error)")
}
}
The compiler gives me the following error:
In argument type 'Obj.Type', 'Obj' does not conform to expected type 'Decodable'
I would have imagine that Obj is decodable due to the where clause.
What is wrong with that function?
Instead of doing a "where" statement, make your life easier by restricting the generic itself:
func assertDecode<Obj: Decodable>(_ type: Obj.Type, fileName: String)