Skip to content

Instantly share code, notes, and snippets.

@isaac-weisberg
Created February 10, 2019 04:33
Show Gist options
  • Select an option

  • Save isaac-weisberg/62dd2eb131dbb26755801059ac329391 to your computer and use it in GitHub Desktop.

Select an option

Save isaac-weisberg/62dd2eb131dbb26755801059ac329391 to your computer and use it in GitHub Desktop.
import Foundation
import Cocoa
/*
SETUP
*/
let payload = """
{
"things": [
null,
{
"number": 3
}
]
}
""".data(using: .utf8)!
struct Number: Decodable {
let number: Double
init?(dictionary: [String: Any]) {
guard let number = dictionary["number"] as? Double else {
return nil
}
self.number = number
}
}
struct Payload: Decodable {
let things: [Number?]
init?(dictionary: [String: Any]) {
guard let things = dictionary["things"] as? [[String: Any]?] else {
return nil
}
/*
Following code does not distinguish between failure of
dictionary casting and failure of actual deserialization into Number
structure. That's why I use a separate `success` flag
*/
var success = true
let numbers = things
.map { dictionary -> Number? in
guard let dictionary = dictionary else {
return nil
}
guard let number = Number(dictionary: dictionary) else {
success = false // means, actual parsing failed
return nil
}
return number
}
guard success else {
return nil
}
self.things = numbers
}
}
/*
ATTEMPTS
*/
let jsonObject = try JSONSerialization.jsonObject(with: payload) as! [String: Any] // this one is guaranteed cast
let parsedObject = Payload(dictionary: jsonObject)
let stuff = parsedObject?.things
// Here, the playgound will be showing proper values, that nils inside array have indeed been parsed successfully
let decoder = JSONDecoder()
let parsedDecodable = try? decoder.decode(Payload.self, from: payload)
let things = parsedDecodable?.things
// Same thing.
// This means that it's the ObjectMapper that is incapable of properly handling nils inside an array and not the Foundation JSONSerialization API.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment