Skip to content

MJModel is a framework in swift which allows you to easily convert model to json string or json string to model.

License

Notifications You must be signed in to change notification settings

Musjoy/Swift-MJModel

Repository files navigation

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

pod 'MJModel'
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"),
]

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, Raymond.huang@musjoy.com

License

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

About

MJModel is a framework in swift which allows you to easily convert model to json string or json string to model.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages