Skip to content

Commit

Permalink
Feat: Add method to decode with keypath #76
Browse files Browse the repository at this point in the history
  • Loading branch information
jinios committed Feb 10, 2019
1 parent 08a3a65 commit b96cd57
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
13 changes: 13 additions & 0 deletions MartHoliday/MartHoliday/Utility/Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,16 @@ extension UIDevice {
}

}

extension JSONDecoder {
func decode<T: Decodable>(_ type: T.Type, from data: Data, keyPath: String) throws -> T {
let toplevel = try JSONSerialization.jsonObject(with: data)
if let nestedJson = (toplevel as AnyObject).value(forKeyPath: keyPath) {
let nestedJsonData = try JSONSerialization.data(withJSONObject: nestedJson)
return try decode(type, from: nestedJsonData)
} else {
throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Nested json not found for key path \"\(keyPath)\""))
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,9 @@ class MainViewController: RechabilityDetectViewController, FavoriteConvertible,
let ids = FavoriteList.shared().ids()
let idstr = ids.map{String($0)}.joined(separator: ",")
guard let urlstr = KeyInfoLoader.loadValue(of: .FavoriteBranchesURL) else { return }
guard let baseURL = URL(string: urlstr) else { return }
let url = baseURL.appendingPathComponent(idstr)
var urlComp = URLComponents(string: urlstr)
urlComp?.queryItems = [URLQueryItem(name: "ids", value: idstr)]
guard let url = urlComp?.url else {return}

let configure = URLSessionConfiguration.default
configure.timeoutIntervalForRequest = 3
Expand All @@ -160,7 +161,7 @@ class MainViewController: RechabilityDetectViewController, FavoriteConvertible,
var favoriteList = BranchList()
var mainFavorites = [FavoriteBranch]()
do {
branches = try JSONDecoder().decode([BranchRawData].self, from: data)
branches = try JSONDecoder().decode([BranchRawData].self, from: data, keyPath: "data")
favoriteList = BranchList(branches: branches)

for fav in favoriteList.branches {
Expand Down

0 comments on commit b96cd57

Please sign in to comment.