Medea
A bag of functions (living in JSONHelper
) for converting to and from JSON representations. It's a very thin wrapper around JSONSerialization
that also:
-
Is explicit about whether JSON is expected to be an object or an array, throwing an error if an unexpected type is encountered.
-
Handles all the conversions between
Data
andString
, eliminating a lot ofOptional
s andguards
in the process. -
Converts some common
JSONSerialization
errors out of theNSCocoaErrorDomain
and into the easier-to-catchJSONError
enum. -
Provides convenience types for
JSONObject
andJSONArray
to save you from having to make sense of obliqueAny
s. -
Provides easy validation functions for verifying
Data
s,String
s,JSONObject
s orJSONArray
s represent well-formed JSON — without having to chain a bunch of conversions andtry
.
Usage
From JSON:
let object = try JSONHelper.jsonObject(from: "{\"foo\": 42}")
let array = try JSONHelper.jsonArray(from: "[42, 64, 10175]")
let isValid = JSONHelper.isValid("{\"numbers\": [1,2,3]}")
try JSONHelper.validate("[1,true,null]")
To JSON:
let jsonString = try JSONHelper.string(from: ["foo": 42])
let jsonData = try JSONHelper.data(from: [42, 64, 10175])
let isValid = JSONHelper.isValid(["invalid": Date()])
try JSONHelper.validate([1, true, NSNull()])
API
Full API documentation can be found here.