MJModel 0.1.1

MJModel 0.1.1

Maintained by Raymond H, Raymond H.



MJModel 0.1.1

  • By
  • raymond-hl

MJModel

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.

CI Status codecov Version License Platform Carthage compatible Gitter

Requirements

  • iOS 8.0+ / Mac OS X 10.9+
  • Xcode 11.0+
  • Swift 5.0+

Installation

CocoaPods :

pod 'MJModel'

Carthage :

github "Musjoy/Swift-MJModel" "master"

Swift Package Manager :

Add the following to your Package.swift file's dependencies:

dependencies: [
    .package(url: "https://github.com/Musjoy/Swift-MJModel.git", from: "0.1.0"),
]

Usage

Import

import MJModel

Model To JSON String

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()!)

JSON String To Model

let jsonString = "{\"name\":\"string\",\"age\":1}"
let modelResult = BaseClass.initWith(jsonString)!
print(modelResult.name!)
print(modelResult.age!)

Extend Other

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!)

Author

raymond-hl, [email protected]

License

MJModel is available under the MIT license. See the LICENSE file for more info.