An elegant, protocol-oriented tool, help convert JSON to Model or vice versa.
final class Student: NSObject, JSONConvertible {
var id = ""
var name = ""
var sampleDigit = ""
var sampleArray = [Int]()
var sampleDic = [String: AnyObject]()
}
let dic = [
"id": "4096",
"name": "Teemo",
"sampleDigit": 666,
"sampleArray": [1, 2, 3, 4, 5, 6],
"sampleDic": ["lang": "Swift", "ver": "2.1"]
]
let student = Student.generateModel(dic)
print(student.id)
// prints 4096
print(student.name)
// prints Teemo
print(student.sampleDigit)
// prints 666
print(student.sampleArray)
// prints [1, 2, 3, 4, 5, 6]
print(student.sampleDic)
// prints ["lang": "Swift", "ver": "2.1"]]
let data = student.convertToDictionary()
print(data)
// prints [
// "id": "4096",
// "name": "Teemo",
// "sampleDigit": 666,
// "sampleArray": [1, 2, 3, 4, 5, 6],
// "sampleDic": ["lang": "Swift", "ver": "2.1"]
//]
- iOS 8.0+
- Xcode 7.2+
Put github "CaptainTeemo/TMModel"
in your cartfile and run carthage update
from terminal, then drag built framework to you project.
That's all.
- Make your model class inheriting from
NSObject
(our implementation depends on the Objective-C Runtime, check source code for details); - Mark your class as
final
; - Conform to protocol
JSONConvertible
, and your class got JSON-to-model convertion (or vice versa) for free; - Declare all properties you need from JSON;
- Please check step 6;
- There's no step 6 :p