在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:JohnSundell/Unbox开源软件地址:https://github.com/JohnSundell/Unbox开源编程语言:Swift 99.1%开源软件介绍:Unbox is deprecated in favor of Swift’s built-in Unbox | Wrap Unbox is an easy to use Swift JSON decoder. Don't spend hours writing JSON decoding code - just unbox it instead! Unbox is lightweight, non-magical and doesn't require you to subclass, make your JSON conform to a specific schema or completely change the way you write model code. It can be used on any model with ease. Basic exampleSay you have your usual-suspect struct User {
let name: String
let age: Int
} That can be initialized with the following JSON: {
"name": "John",
"age": 27
} To decode this JSON into a struct User {
let name: String
let age: Int
}
extension User: Unboxable {
init(unboxer: Unboxer) throws {
self.name = try unboxer.unbox(key: "name")
self.age = try unboxer.unbox(key: "age")
}
} Unbox automatically (or, actually, Swift does) figures out what types your properties are, and decodes them accordingly. Now, we can decode a let user: User = try unbox(dictionary: dictionary) or even: let user: User = try unbox(data: data) Advanced exampleThe first was a pretty simple example, but Unbox can decode even the most complicated JSON structures for you, with both required and optional values, all without any extra code on your part: struct SpaceShip {
let type: SpaceShipType
let weight: Double
let engine: Engine
let passengers: [Astronaut]
let launchLiveStreamURL: URL?
let lastPilot: Astronaut?
let lastLaunchDate: Date?
}
extension SpaceShip: Unboxable {
init(unboxer: Unboxer) throws {
self.type = try unboxer.unbox(key: "type")
self.weight = try unboxer.unbox(key: "weight")
self.engine = try unboxer.unbox(key: "engine")
self.passengers = try unboxer.unbox(key: "passengers")
self.launchLiveStreamURL = try? unboxer.unbox(key: "liveStreamURL")
self.lastPilot = try? unboxer.unbox(key: "lastPilot")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"
self.lastLaunchDate = try? unboxer.unbox(key: "lastLaunchDate", formatter: dateFormatter)
}
}
enum SpaceShipType: Int, UnboxableEnum {
case apollo
case sputnik
}
struct Engine {
let manufacturer: String
let fuelConsumption: Float
}
extension Engine: Unboxable {
init(unboxer: Unboxer) throws {
self.manufacturer = try unboxer.unbox(key: "manufacturer")
self.fuelConsumption = try unboxer.unbox(key: "fuelConsumption")
}
}
struct Astronaut {
let name: String
}
extension Astronaut: Unboxable {
init(unboxer: Unboxer) throws {
self.name = try unboxer.unbox(key: "name")
}
} Error handlingDecoding JSON is inherently a failable operation. The JSON might be in an unexpected format, or a required value might be missing. Thankfully, Unbox takes care of handling both missing and mismatched values gracefully, and uses Swift’s You don’t have to deal with multiple error types and perform any checking yourself, and you always have the option to manually exit an unboxing process by Supported typesUnbox supports decoding all standard JSON types, like:
It also supports all possible combinations of nested arrays & dictionaries. As you can see in the Advanced example above (where an array of the unboxable Finally, it also supports TransformationsUnbox also supports transformations that let you treat any value or object as if it was a raw JSON type. It ships with a default The same is also true for To enable your own types to be unboxable using a transformation, all you have to do is make your type conform to Here’s an example that makes a native Swift struct UniqueIdentifier: UnboxableByTransform {
typealias UnboxRawValueType = String
let identifierString: String
init?(identifierString: String) {
if let UUID = NSUUID(uuidString: identifierString) {
self.identifierString = UUID.uuidString
} else {
return nil
}
}
static func transform(unboxedValue: String) -> UniqueIdentifier? {
return UniqueIdentifier(identifierString: unboxedValue)
}
} FormattersIf you have values that need to be formatted before use, Unbox supports using formatters to automatically format an unboxed value. Any enum Currency {
case usd(Int)
case sek(Int)
case pln(Int)
}
struct CurrencyFormatter: UnboxFormatter {
func format(unboxedValue: String) -> Currency? {
let components = unboxedValue.components(separatedBy: ":")
guard components.count == 2 else {
return nil
}
let identifier = components[0]
guard let value = Int(components[1]) else {
return nil
}
switch identifier {
case "usd":
return .usd(value)
case "sek":
return .sek(value)
case "pln":
return .pln(value)
default:
return nil
}
}
} You can now easily unbox any struct Product: Unboxable {
let name: String
let price: Currency
init(unboxer: Unboxer) throws {
name = try unboxer.unbox(key: "name")
price = try unboxer.unbox(key: "price", formatter: CurrencyFormatter())
}
} Supports JSON with both Array and Dictionary root objectsNo matter if the root object of the JSON that you want to unbox is an Built-in enum supportYou can also unbox enum Profession: Int, UnboxableEnum {
case developer
case astronaut
} Now struct Passenger: Unboxable {
let profession: Profession
init(unboxer: Unboxer) throws {
self.profession = try unboxer.unbox(key: "profession")
}
} Contextual objectsSometimes you need to use data other than what's contained in a dictionary during the decoding process. For this, Unbox has support for strongly typed contextual objects that can be made available in the unboxing initializer. To use contextual objects, make your type conform to Key path supportYou can also use key paths (for both dictionary keys and array indexes) to unbox values from nested JSON structures. Let's expand our User model: {
"name": "John",
"age": 27,
"activities": {
"running": {
"distance": 300
}
},
"devices": [
"Macbook Pro",
"iPhone",
"iPad"
]
} struct User {
let name: String
let age: Int
let runningDistance: Int
let primaryDeviceName: String
}
extension User: Unboxable {
init(unboxer: Unboxer) throws {
self.name = try unboxer.unbox(key: "name")
self.age = try unboxer.unbox(key: "age")
self.runningDistance = try unboxer.unbox(keyPath: "activities.running.distance")
self.primaryDeviceName = try unboxer.unbox(keyPath: "devices.0")
}
} You can also use key paths to directly unbox nested JSON structures. This is useful when you only need to extract a specific object (or objects) out of the JSON body. {
"company": {
"name": "Spotify",
},
"jobOpenings": [
{
"title": "Swift Developer",
"salary": 120000
},
{
"title": "UI Designer",
"salary": 100000
},
]
} struct JobOpening {
let title: String
let salary: Int
}
extension JobOpening: Unboxable {
init(unboxer: Unboxer) throws {
self.title = try unboxer.unbox(key: "title")
self.salary = try unboxer.unbox(key: "salary")
}
}
struct Company {
let name: String
}
extension Company: Unboxable {
init(unboxer: Unboxer) throws {
self.name = try unboxer.unbox(key: "name")
}
} let company: Company = try unbox(dictionary: json, atKey: "company")
let jobOpenings: [JobOpening] = try unbox(dictionary: json, atKey: "jobOpenings")
let featuredOpening: JobOpening = try unbox(dictionary: json, atKeyPath: "jobOpenings.0") Custom unboxingSometimes you need more fine grained control over the decoding process, and even though Unbox was designed for simplicity, it also features a powerful custom unboxing API that enables you to take control of how an object gets unboxed. This comes very much in handy when using Unbox together with Core Data, when using dependency injection, or when aggregating data from multiple sources. Here's an example: let dependency = DependencyManager.loadDependency()
let model: Model = try Unboxer.performCustomUnboxing(dictionary: dictionary, closure: { unboxer in
var model = Model(dependency: dependency)
model.name = try? unboxer.unbox(key: "name")
model.count = try? unboxer.unbox(key: "count")
return model
}) InstallationCocoaPods: Add the line Carthage: Add the line Manual: Clone the repo and drag the file Swift Package Manager: Add the line Platform supportUnbox supports all current Apple platforms with the following minimum versions:
Debugging tipsIn case your unboxing code isn’t working like you expect it to, here are some tips on how to debug it: Compile time error: Swift cannot find the appropriate overload of the
Use the do {
let model: Model = try unbox(data: data)
} catch {
print("An error occurred: \(error)")
} If you need any help in resolving any problems that you might encounter while using Unbox, feel free to open an Issue. Community Extensions
Hope you enjoy unboxing your JSON!For more updates on Unbox, and my other open source projects, follow me on Twitter: @johnsundell Also make sure to check out Wrap that let’s you easily encode JSON. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论