Unbox maps your JSON to structures or classes, therefore you have to have a struct/class that conforms to Unboxable
protocol. For example:
struct Item: Unboxable {
var id: String
var name: String
init(unboxer: Unboxer) throws {
self.id = try unboxer.unbox(key: "id")
self.name = try unboxer.unbox(key: "name")
}
}
Then you can use it like so (provided URL serves your JSON example):
let url = URL(string: "https://api.myjson.com/bins/o8b4t")
let task = URLSession.shared.dataTask(with: url!) { data, _, _ in
if let data = data {
if let items: [Item] = try? unbox(data: data) {
print(items.count, items.first?.name)
// Output: 2 Optional("Spotify")
}
}
}
task.resume()
As for raw dictionaries or arrays, IMO there's no point of using Unbox for that, just use JSONSerialization.jsonObject(with:)
, like this:
let url = URL(string: "https://api.myjson.com/bins/o8b4t")
let task = URLSession.shared.dataTask(with: url!) { data, _, _ in
if let data = data {
if let parsed = (try? JSONSerialization.jsonObject(with: data)) as? [[String: String]] {
print(parsed.count, parsed.first?["name"])
// Output: 2 Optional("Spotify")
}
}
}
task.resume()
Note: In real world you'd prefer catching thrown exceptions (if any).