In Android development, third-party conversion libraries such as Gson are available. Of course, there are some libraries such as Mjextensiond in iOS. Here, I only use the official simple KVC mode to achieve it.
First, build a model and inherit NSObject, the code is as follows:
classuser:nsobject{
var name:string?
var sex:string?
var age:int=0
Override Func SetValue (_value:any, Forundefinedkey key:string) {
}
}
Second, in the controller to test
classtestviewcontroller:uiviewcontroller{
Overridefuncviewdidload () {
Super.viewdidload ()
Let dic = ["name": "Zhang San", "Sex": "Male", "Age": "20"]
Let user =user ()
User.setvaluesforkeys (DIC)
Print ("-conversion result--", user.name!, "---", user.sex!, "---", user.age)
}
Overridefuncdidreceivememorywarning () {
Super.didreceivememorywarning ()
}
}
After running, you can see
- Conversion Results -- Zhang San --- male ---
Attention:
But there is a problem, when our JSON data field is superfluous in our model field when the direct crash (that is, to correspond, or error). This is obviously not what we want, because in the actual development, we will only take the part of the data we want, the other we do not need, how to solve the problem is actually simple, just need to rewrite a SetValue method in our model can filter out the fields without the code is as follows:
classuser:nsobject{
Varname:string?
Varsex:string?
Varage:int=0
Varno:string?
Override Func SetValue (_value:any, Forundefinedkey key:string) {
}
}
After rewriting, we test the dictionary by adding a field to the test.
classtestviewcontroller:uiviewcontroller{
Overridefuncviewdidload () {
Super.viewdidload ()
Letdic = ["Name": "Zhang San", "Sex": "Male", "age": "+", "no": "+", "a": "WX"]
Letuser =user ()
User.setvaluesforkeys (DIC)
Print ("-conversion result--", user.name!, "---", user.sex!, "---", user.age,user.no!)
}
Overridefuncdidreceivememorywarning () {
Super.didreceivememorywarning ()
}
}
Operation without error, the result is:- conversion Results -- Zhang San --- male ---
This is a simple KVC implementation of JOSN and model conversion examples, if you have questions welcome message!
Jane Book Address: Http://www.jianshu.com/p/99d302396ee9
iOS KVC JSON to model simple reality