Skip to content

Instantly share code, notes, and snippets.

@HassanSE
Created September 27, 2017 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HassanSE/fb512fc21959807beb4f0686abf8220c to your computer and use it in GitHub Desktop.
Save HassanSE/fb512fc21959807beb4f0686abf8220c to your computer and use it in GitHub Desktop.
//
// JSONParsing.swift
// hplus-sports
//
// Created by Muhammad Hassan on 9/27/17.
// Copyright © 2017 Lynda.com. All rights reserved.
//
import Foundation
enum JSONParsingError: Error {
case missingKey(key: String)
case typeMismatch(key: String)
}
protocol JSONDecodable {
init(_ decoder: JSONDecoder) throws
}
typealias JSONObject = [String: Any]
class JSONDecoder {
let jsonObject: JSONObject
static let defaultDataFormat = "dd/MM/yyyy HH:mm:ss"
private lazy var dateFormatter = DateFormatter()
init(_ jsonObject: JSONObject) {
self.jsonObject = jsonObject
}
func value<T>(forKey key: String) throws -> T {
guard let value = jsonObject[key] else {
throw JSONParsingError.missingKey(key: key)
}
guard let finalValue = value as? T else {
throw JSONParsingError.typeMismatch(key: key)
}
return finalValue
}
func value(forKey key: String, format: String = JSONDecoder.defaultDataFormat) throws -> Date {
let dateValue: String = try value(forKey: "date")
dateFormatter.dateFormat = format
guard let returnValue = dateFormatter.date(from: dateValue) else {
throw JSONParsingError.typeMismatch(key: key)
}
return returnValue
}
}
func parse<T>(_ data: Data) throws -> [T] where T: JSONDecodable {
let jsonObjects: [JSONObject] = try deserialize(data)
return try jsonObjects.map(decode)
}
func deserialize(_ data: Data) throws -> [JSONObject] {
let json = try JSONSerialization.jsonObject(with: data, options: [])
guard let objects = json as? [JSONObject] else { return [] }
return objects
}
func decode<T>(_ jsonObject: JSONObject) throws -> T where T: JSONDecodable {
return try T.init(JSONDecoder(jsonObject))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment