MJModel is a framework which allows you to easily convert model to json string or json string to model.
MJModel supports class and struct, and no need to inherit from NSObject. By replacing KVC in NSObject, it directly operate memory to get or set values. And it use Mirror in Swift to get all properties in model.
MJModel is defined as a protocol, so you can use it simply just like protocol. Only one extension of the existed model can do the trick.
- iOS 8.0+ / Mac OS X 10.9+
- Xcode 11.0+
- Swift 5.0+
pod 'MJModel'
Carthage :
github "Musjoy/Swift-MJModel" "master"
Add the following to your Package.swift file's dependencies:
dependencies: [
.package(url: "https://github.com/Musjoy/Swift-MJModel.git", from: "0.1.0"),
]
import MJModel
class BaseClass : Model {
var name : String?
var age : Int?
required init() {}
}
let model = BaseClass()
model.name = "string"
model.age = 1
print(model.toDictionary())
print(model.toJSONString()!)
let jsonString = "{\"name\":\"string\",\"age\":1}"
let modelResult = BaseClass.initWith(jsonString)!
print(modelResult.name!)
print(modelResult.age!)
struct ExtendOtherStruct {
var name : String?
var age : Int?
}
extension ExtendOtherStruct : Model {}
var model = ExtendOtherStruct()
model.name = "string"
model.age = 1
let jsonString = model.toJSONString();
let modelResult = ExtendOtherStruct.initWith(jsonString!)!
print(jsonString!)
print(modelResult.name!)
print(modelResult.age!)
raymond-hl, Raymond.huang@musjoy.com
MJModel is available under the MIT license. See the LICENSE file for more info.