MappingJSON是一个用Swift编写的框架,用于将JSON映射到您的对象,使这一过程变得容易。
对象只需要实现Object
协议以进行映射。
import MappingJSON
struct User: Object {
var id: Int
var name: String
var email: String
var age: Int?
// Object protocol
static func map(json: MappingJSON) throws -> User {
return try User(
id: json.value("id"),
name: json.value("name"),
email: json.value("email"),
age: json.optionalValue("age")
)
}
}
如下将JSON转换为您的对象。
let rawJSON = [String: AnyObject] = [
"id": 1,
"name": "William",
"email": "[email protected]",
"age": 22
]
// initialize MappingJSON with raw JSON object
let json = MappingJSON(raw: rawJSON)
// pass your object type to 'map' function
let user = try? json.map(User)
print(user.email) // shows '[email protected]' to you console!
您可以将JSON中的原始值转换为任何您喜欢的对象。
要转换,只需将闭包添加到value
或optionalValue
函数的第二个参数中。
struct User: Object {
var id: Int
var name: String
var email: String
var age: Int?
var birthday: NSDate?
// Object protocol
static func map(json: MappingJSON) throws -> User {
return try User(
id: json.value("id"),
name: json.value("name"),
email: json.value("email"),
age: json.optionalValue("age"),
birthday: json.optionalValue("birthday", transform: dateTransform)
)
}
}
static let dateTransform = {(timestamp: NSTimeInterval) in
NSDate(timeIntervalSince1970: timestamp)
}
MappingJSON以MIT协议发布。