DecodeStrategy is convenient applying decode strategy if your backend uses weak type language.
-
Value has default value, if decode failure
-
Element of array ignore, if decode failure
-
Element of array has default value, if decode failure
-
Universal decode with String, Int and Double type
-
Manually
Add the Sources folder to your Xcode project.
-
CocoaPods
pod 'DecodeStrategy'
- You can use
EmptyString
,ZeroInt
,ZeroDouble
struct User: Decodable {
@DecodeHasDefault<EmptyString>
var name: String
}
let data = #"{ "name": null }"#.data(using: .utf8)!
let result = try JSONDecoder().decode(User.self, from: data)
print(result.name)
// ""
- Or custom your provider
struct User: Decodable {
struct DefaultName: DecodeDefaultProvider {
static var defaultValue = "Ohlulu"
}
@DecodeHasDefault<DefaultName>
var name: String
}
let data = #"{ "name": null }"#.data(using: .utf8)!
let result = try JSONDecoder().decode(User.self, from: data)
print(result.name)
// "Ohlulu"
struct Model: Decodable {
@DecodeUniversal var intValue: Int
}
let data = #"{ "intValue": "100" }"#.data(using: .utf8)!
let model = try JSONDecoder().decode(Model.self, from: data)
print(model.intValue)
// 100
struct Model: Decodable {
@DecodeUniversal var strValue: String
}
let data = #"{ "strValue": 100 }"#.data(using: .utf8)!
let model = try JSONDecoder().decode(Model.self, from: data)
print(model.strValue)
// "100"
struct Model: Decodable {
@DecodeArrayIgnore var arr: [String]
}
let data = #"{ "arr": ["1", 2, "3", null] }"#.data(using: .utf8)!
let model = try JSONDecoder().decode(Model.self, from: data)
print(model.arr)
// ["1", "3"]
struct Model: Decodable {
struct DefauleString: DecodeDefaultProvider {
static var defaultValue = "-1"
}
@DecodeArrayHasDefault<DefauleString> var arr: [String]
}
let data = #"{ "arr": ["1", 2, "3", null] }"#.data(using: .utf8)!
let model = try JSONDecoder().decode(Model.self, from: data)
print(model.arr)
// ["1", "-1", "3", "-1"]
DecodeStrategy is released under the MIT license. See LICENSE for details.