Skip to content

Instantly share code, notes, and snippets.

@juliaYamamoto
Last active December 15, 2020 21:41
Show Gist options
  • Save juliaYamamoto/e1bdddb8be40b86454077dc79c4ffa74 to your computer and use it in GitHub Desktop.
Save juliaYamamoto/e1bdddb8be40b86454077dc79c4ffa74 to your computer and use it in GitHub Desktop.
Parse a local json using generics
// Static function to decode a local json
// Receives a path and a generic type (must conform to the codable protocol) and return the data decoded into the given type
class JsonParser {
static func from<T: Codable> (path: String, ofType: T.Type) -> T? {
guard let jsonPath = Bundle.main.path(forResource: path, ofType: "json") else { return nil }
do {
guard let jsonData = try String(contentsOfFile: jsonPath).data(using: .utf8) else {
return nil
}
let decodedData = try JSONDecoder().decode(ofType.self, from: jsonData)
return decodedData
} catch {
print(error)
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment