Last active
March 14, 2016 04:43
-
-
Save ikesyo/927a17b96ee289d860cc to your computer and use it in GitHub Desktop.
Convert a JSON string into a valid JSON object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://twitter.com/watura/status/708164552882425856 | |
import Himotoki | |
struct Foo: Decodable { | |
let JSON: [String: AnyJSON] | |
static func decode(e: Extractor) throws -> Foo { | |
let dictFromJSONStringTransformer = Transformer<String, [String: AnyJSON]> { string in | |
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else { | |
throw customError("Failed to convert a string to a data: \(string)") | |
} | |
let JSON = try NSJSONSerialization.JSONObjectWithData(data, options: []) | |
guard let JSONDict = JSON as? [String: AnyJSON] else { | |
throw typeMismatch("\([String: AnyJSON].self)", actual: JSON, keyPath: nil) | |
} | |
return JSONDict | |
} | |
return try self.init(JSON: dictFromJSONStringTransformer.apply(e <| "json_string")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment