4 ms·
I agree with this and I've raised it several times in Objective-C codebases that can some times end up littered with NSDictionary:s everywhere taking no advanta
by K0nserv 10y ago
I agree with this and I've raised it several times in Objective-C codebases that can some times end up littered with NSDictionary:s everywhere taking no advantage of the Objective-C type mechanics. I don't think it's necessarily as bad in python or javascript. This is because these languages are dynamically typed and that diminishes the benefits of deserializing json to a native model. It's still valuable because you can guard against bad data by rejecting at the boundary of your program.
In statically typed languages however the added bonus is a lot more significant because the type system increases the benefits of deserializing JSON to native models. Take this Swift example
import Foundation
enum SerializationError: ErrorType {
case InvalidData
}
struct Thing {
let a: Int
let b: String
static func deserialize(fromDictionary data: [String:AnyObject]) throws -> Thing {
guard let a = data["a"] as? Int, let b = data["b"] as? String else {
throw SerializationError.InvalidData
}
return Thing(a: a, b: b)
}
static func deserialize(fromArray data: [[String: AnyObject]]) -> [Thing] {
return data.flatMap {
try? deserialize(fromDictionary: $0)
}
}
}
let data: [[String: AnyObject]] = [
[
"a": 10 as NSNumber,
"b": "Hello" as NSString
],
[
"a": "10" as NSString,
"b": 10 as NSNumber
]
]
let models = Thing.deserialize(fromArray: data)
Not only do you end up with a native array of models you can also be certain that any type information is correct because invalid results have been thrown away during parsing.
- xyzzy4 10y agoIt's good to use lots of NSDictionary's in Objective C, in my opinion. The alternative is to create lots of different object types that takes much more code, and very little benefit for that extra code. If you're just shifting data around then there's no need to define objects for them.