{
"rabbets": ["0.100-0.300", "0.301-0.500"]
}
class SomeObject: HandyJSON {
class Rabbet: HandyJSON {
var begin: String?
var end: String?
required init() {}
init(begin: String, end: String) {
self.begin = begin
self.end = end
}
}
var rabbets: [Rabbet]?
required init() {}
public func mapping(mapper: HelpingMapper) {
mapper <<<
rabbets <-- ("rabbets", TransformOf<[Rabbet], [String]>(fromJSON: { (raw) -> [Rabbet]? in
return raw?.compactMap { item -> Rabbet? in
let splited = item.split(separator: "-")
guard splited.count == 2 else { return nil }
return Rabbet(begin: String(splited[0]), end: String(splited[1]))
}
} , toJSON: { rabbets -> [String]? in
return rabbets?.compactMap { item -> String? in
guard let begin = item.begin, let end = item.end else { return nil }
return "\(begin)-\(end)"
}
}))
}
required init(from decoder: Decoder) throws {
let contaier = try decoder.container(keyedBy: CodingKeys.self)
var unkeyed = try contaier.nestedUnkeyedContainer(forKey: .rabbets)
var arr: [Rabbet] = []
while !unkeyed.isAtEnd {
let item = try unkeyed.decode(String.self)
let splited = item.split(separator: "-")
if splited.count == 2 {
arr.append(Rabbet(begin: String(splited[0]), end: String(splited[1])))
}
}
self.rabbets = arr
}
}
extension SomeObject: Decodable{
enum CodingKeys: String, CodingKey {
case rabbets
}
}
let json = """
{
"rabbets": ["0.100-0.300", "0.301-0.500"]
}
"""
if let type = SomeObject.deserialize(from: json), let result = type.toJSONString(prettyPrint: true) {
print(result)
}
let decoder = JSONDecoder()
let obj = try? decoder.decode(SomeObject.self, from: json.data(using: .utf8)!)
如何让model兼容多个版本的API
Swift 4 JSON decode with configurable keys