Function
By customizing the model base class, you implement:
1. Convert the JSON dictionary to an object without having to consider the relationship between the name of the property name and the dictionary key (key), that is, you can customize the mapping relationship. The assignment of custom objects in dictionaries is also supported.
2. A line of code converts the object to a JSON dictionary.
Use
Let the custom model class inherit from Cyzbasemodel. Then choose the method to override or invoke as needed.
Dictionary to object:
1. If the name of the key in the dictionary is the same as the property name of the object, you do not need to re-use any methods or attributeMapDictionary return nil in.
2. If the name of any of the keys in the dictionary is not the same as the object property, you will need to establish the mapping dictionary yourself, in which you attributeMapDictionary return a dictionary class object that you created, with the property name as key and the key for the "map Dictionary" (that is, the incoming dictionary) as value. It may sound a bit more round, and the details will be known at the code.
3. If there is a custom object, setAttributeDictionary: remove the dictionary from the dictionary and use it to create the object, then assign the value.
4, regardless of the above situation, when creating your custom object using the initWithDict: method, the incoming dictionary can be automatically turned into an object.
object to Dictionary:
The method dictionaryRepresentation can be called
Implementation ideas
The main point of knowledge is reflection, or OBJC's runtime knowledge. object to the dictionary, to get all the properties in the object, and then save the property name and property values in a dictionary. The dictionary to the object, is the first according to their own definition of the mapping Dictionary (map Dictionary) to convert its own property name to the name of the key to be converted to the dictionary, and then according to the name of its own property to obtain setter method, the dictionary to be converted into the value taken out as a setter parameter call on the line.
Code
object to Dictionary:
- (nsdictionary*) Dictionaryrepresentation {unsigned intCount =0;//get A list of all properties of the This classobjc_property_t *properties = Class_copypropertylist ([ SelfClass], &count);nsmutabledictionary*dict = [nsmutabledictionaryDictionarywithcapacity:count];nsdictionary*keyvaluemap = [ SelfAttributemapdictionary]; for(inti =0; I < count; i++) {NSString*key = [NSStringStringwithutf8string:property_getname (Properties[i]);IDValue = [ SelfValueforkey:key];NSLog(@"key =%@, value =%@, value class =%@, changed key =%@", key, Value, Nsstringfromclass ([value class]), [Keyvaluemap Objectforkey:key]); key = [Keyvaluemap Objectforkey:key];//only Add it to dictionary if it 's not nil if(Key && value) {[Dict setobject:value forkey:key]; }} free (properties);returnDict;}
Dictionary to object:
- (ID) Initwithdict: (nsdictionary*) adict{ Self= [SuperINIT];if( Self) {//Establish mapping relationship[ SelfSETATTRIBUTESDICTIONARY:ADICT]; }return Self;} - (nsdictionary*) attributemapdictionary{//Subclasses need to override the method //nsassert (NO, "should override this method in Your Custom Class"); return Nil;} - (void) Setattributesdictionary: (nsdictionary*) adict{//Get a mapping dictionary nsdictionary*mapdictionary = [ SelfAttributemapdictionary];//If the subclass does not override the Attributemapdictionary method, the default mapping dictionary is used if(Mapdictionary = =Nil) {nsmutabledictionary*tempdict = [nsmutabledictionaryDictionarywithcapacity:adict. Count]; for(NSString*key in adict) {[tempdict setobject:key forkey:key]; } mapdictionary = Tempdict; }//Traversal mapping dictionaryNsenumerator *keyenumerator = [Mapdictionary keyenumerator];IDAttributeName =Nil; while((AttributeName = [Keyenumerator nextobject])) {//Get property setterSEL setter = [ Self_getsetterwithattributename:attributename];if([ SelfRespondstoselector:setter]) {//Get the value of the mapping dictionary, which is the key to the dictionary NSString*adictkey = [Mapdictionary objectforkey:attributename];//Gets the value corresponding to the key of the incoming dictionary, which is the value to assign to the property IDAdictvalue = [Adict Objectforkey:adictkey];//Assign a value to a property[ SelfPerformselectoronmainthread:setter Withobject:adictvalue waituntildone:[NsthreadIsmainthread]]; }}}-(SEL) _getsetterwithattributename: (NSString*) attributename{NSString*firstalpha = [[AttributeName substringtoindex:1] uppercasestring];NSString*otheralpha = [AttributeName substringfromindex:1];NSString*settermethodname = [NSStringstringwithformat:@"set%@%@:", Firstalpha, Otheralpha];returnNsselectorfromstring (settermethodname);}
Download
Project Address: Https://github.com/YiZhuoChen/CYZBaseModel
iOS development--convert objects and dictionaries to each other