ModelSwift can convert josn (or Data) to model in Swift.
example:
class User: NSObject {
var name: String?
var age = 0 // not var age: Int?
var desc: String?
}
class Repos: NSObject {
var title: String?
var owner: User?
var viewers: [User]?
}
You can map a json key to a property name. just like this:
// JSON
{
"title": "ModelSwift",
"owner": { "name": "hujewelz", "age": 23, "description": "iOS Developer" },
"viewers": [
{ "name": "hujewelz", "age": 23, "description": "iOS Developer"},
{ "name": "bob", "age": 24 },
{ "name": "jobs", "age": 54 }
]
}
var desc: String?
...
extension User: Replacable {
var replacedProperty: [String : String] {
return ["desc": "description" ]
}
}
var owner: User? // an object
...
extension Repos: Reflectable {
var reflectedObject: [String : AnyClass] {
return ["owner": User.self]
}
}
var viewers: [User]? // an object array
...
extension Repos: ObjectingArray {
var objectInArray: [String : AnyClass] {
return ["viewers": User.self]
}
}
extension User: Ignorable {
/// the store properties can not to be converted.
var ignoredProperty: [String] {
return ["name"]
}
}
If the type of an object in json cannot be matched to the property of the model, it can be coverted too.
eg.
// JSON
{
"name": "jewelz"
"age": "24" // string => Int
"isNew": "1223" // string => Bool
}
// model
var name: String?
var age = 0 // 24
var isNew = false // true
When we got the data from our server, we can use
func ~><T: NSObject>(lhs: Any, rhs: T.Type) -> T?
or func =><T: NSObject>(lhs: Any, rhs: T.Type) -> [T]?
to convert it to model or a model array:
// convert to a model object
if let repos = dict ~> Repos.self {
print(repos)
}
// convert to a model array
if let users = array => User.self {
print(users)
}
To run the example project, clone the repo, and run pod install
from the Example directory first.
- iOS 8.0+
- Xcode 8.1+
- Swift 3.0+
ModelSwift is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "ModelSwift"
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
To integrate ModelSwift into your Xcode project using Carthage, specify it in your Cartfile:
github "hujewelz/modelSwift"
hujewelz
ModelSwift is available under the MIT license. See the LICENSE file for more info.