I’ve been playing around with Gloss, a Swift JSON parser.
I’m liking the mechanics of it a bit better than SwiftyJSON
for a few reasons:
More concise code
Takes its arguments as [String: AnyObject], which works nicely
with the native types of NSJSONSerialization and CouchBase Lite
One of my perennial problems with JSON parsing in Swift is mixed
collections of objects. For example, maybe you have a collection of
Shapes. Some of them are Circles, some are Squares. They may be in
an arbitrary order. When you parse them out of the JSON, you want
them to be the proper subtypes.
I think Gloss lends itself to a pretty nice Factory pattern solution
to this problem…
Here we have our supertype. It has a factory method, and a mapping
from subtype name to Type.
There’s nothing special about our subclasses.
The subclasses must be registered with the factory. It would be
nice to do this when the class is created, but Swift doesn’t offer
us something like +initialize. This can go somewhere like the
AppDelegate’s launch method.
So far I haven’t mentioned Gloss. With Gloss, we can add decoder
methods and <~~ convenience operators.
This lets us parse those varied collections as cleanly as: