Compatibility
- 0.2.0 and master5.35.25.15.04.2
- 0.2.0 and masteriOSmacOS(Intel)macOS(ARM)LinuxtvOSwatchOS
A significant enhancement to the current Codable protocol for better and easier Serializing and Deserializing of JSON
Features:
init(from decoder: Decoder)
struct Foo: Serializable {
@Serialized
var bar: String
@Serialized("globalId")
var id: String?
@Serialized(alternateKey: "mobileNumber")
var phoneNumber: String?
@Serialized(default: 0)
var score: Int
}
Add this line to your Podfile
:
pod 'SerializedSwift'
If you are using SPM for your dependency manager, add this to the dependencies in your Package.swift
file:
dependencies: [
.package(url: "https://github.com/dejanskledar/SerializedSwift.git")
]
class User: Serializable {
@Serialized
var name: String
@Serialized("globalId")
var id: String?
@Serialized(alternateKey: "mobileNumber")
var phoneNumber: String?
@Serialized(default: 0)
var score: Int
required init() {}
}
No additional decoding logic needed
class PowerUser: User {
@Serialized
var powerName: String?
@Serialized(default: 0)
var credit: Int
}
No additional decoding logic needed
class ChatRoom: Serializable {
@Serialized
var admin: PowerUser?
@Serialized(default: [])
var users: [User]
}
You can create own custom Transformable classes, for custom transformation logic.
class DateTransformer: Transformable {
static func transformFromJSON(from value: String?) -> Date? {
let formatter = DateFormatter()
return formatter.date(from: value ?? "")
}
static func transformToJson(from value: Date?) -> String? {
let formatter = DateFormatter()
return formatter.string(from: value ?? Date())
}
}
struct User: Serializable {
@SerializedTransformable<DateTransformer>
var birthDate: Date?
}
Serializable
SerializableEncodable
& SerializableDecodable
Serialized
nil
. For non-optionals, default value is recommended, to avoid crashes@Serialized("mainKey", alternativeKey: "backupKey", default: "")
var key: String?
SerializedTransformable
class DateTransformer: Transformable {
static func transformFromJSON(from value: String?) -> Date? {
let formatter = DateFormatter()
return formatter.date(from: value ?? "")
}
static func transformToJson(from value: Date?) -> String? {
let formatter = DateFormatter()
return formatter.string(from: value ?? "")
}
}
// Usage of `SerializedTransformable`
struct User: Serializable {
@SerializedTransformable<DateTransformer>
var birthDate: Date?
}
This is only a tip of the iceberg of what can one achieve using Property Wrappers and how we can improve Decoding and Encoding JSON in Swift. Feel free to colaborate.