Jsonmodel is a library that parses the JSON data returned by the server.
http://blog.csdn.net/dyllove98/article/details/9050905
Typically, the JSON data returned by the server is converted to model by writing a Data transformation module to convert the NSString data into the data type of the property in the model.
This way the server may need to change two or three files if it wants to make a change.
The appearance of Jsonmodel is to make this kind of parsing work done at the design level.
How to use: Reference connection
The core part of its source code JSONMODEL.M did the source reading, notes as follows:
In
-(ID) initwithdictionary: (nsdictionary*) dict error: (nserror**) Err
All parsing work is done in the function: if there are any errors or errors, return nil directly.
-(ID) initwithdictionary: (nsdictionary*) dict error: (nserror**) err{//1, do validity judgment (Dict is not empty Ah, dict is really a nsdictionary)/ /check for nil input if (!dict) {if (err) *err = [Jsonmodelerror Errorinputisnil]; return nil; }//invalid input, just create empty instance if (![ Dict Iskindofclass:[nsdictionary class]] {if (err) *err = [Jsonmodelerror errorinvaliddata]; return nil; }//create a class instance self = [super init]; if (!self) {//super init didn ' t succeed if (err) *err = [Jsonmodelerror errormodelisinvalid]; return nil; The mapping table for class properties is established by calling __restrospectproperties in//__setup__, and stored in the global variable classproperties inside//->__restrospectproperties using R Untime function to make a list of properties://-Get the attribute list class_copypropertylist (get objc_property_t array), for each objc_property_ T call Property_getname to get the name, Property_getattributes gets the description of the property (string), gets the type of the property by parsing the string, whether it is mutable, whether it is a basic JSON type, etc. Call [class superclass] to get the parent class to continue getting the list// -a list is saved in the Classproperties alternate//-> call +keymapper get the key conversion list, generate Jsonkeymapper object to deposit Keymapper. Do initial class Setup, Retrospec properties [self __setup__]; See if the required arguments are in the input parameters. Check if all required properties is present nsarray* Incomingkeysarray = [Dict AllKeys]; nsmutableset* requiredproperties = [self __requiredpropertynames]; nsset* Incomingkeys = [Nsset Setwitharray:incomingkeysarray]; Get the key mapper jsonkeymapper* keymapper = keymappers[__classname_]; Transform the key names, if neccessary if (keymapper) {//contrast dict input KeyName import nsset with Keymapper object in the Conversion of Yname. A uniform conversion to an object's PropertyName. nsmutableset* Transformedincomingkeys = [Nsmutableset setWithCapacity:requiredProperties.count]; nsstring* transformedname = nil; Loop over the required properties list for (nsstring* requiredpropertyname in requiredproperties) {// Get the mapped key path transformedname = kEymapper.modeltojsonkeyblock (Requiredpropertyname); Chek if exists and if so, add to incoming keys if ([Dict valueforkeypath:transformedname]) {[ Transformedincomingkeys Addobject:requiredpropertyname]; }}//overwrite the raw incoming list with the mapped key names Incomingkeys = Transformedinc Omingkeys; }//Use Nsset's Issubsetofset: Compare the required parameter table with the input KeyName table. If the include relationship is not included, the parameter is not passed enough. Check for missing input keys if (![ Requiredproperties Issubsetofset:incomingkeys]) {//get A list of the missing properties [requiredproperties Minusset:incomingkeys]; Not all required properties is In-invalid input jmlog (@ "Incoming data was invalid [%@ initwithdictionary:]. Keys missing:%@ ", Self._classname_, requiredproperties); if (err) *err = [Jsonmodelerror errorinvaliddatawithmissingkeys:requiredproperties]; return nil; }//not needed anymore incomingkeys= Nil; requiredproperties= Nil; Loop from the object's Classproperties list to Dict: (Assignment uses the setvalue:forkey of the KVO operation: To do so, the setter function assignment is called directly)//loop over the incoming keys and set Self's properties for (jsonmodelclassproperty* property in [self __properties__]) {//For each object's property, pass Over Keymapper conversion to find the corresponding Dict property Dictkeypath, find the value jsonvalue. If there is no value, and this attribute is optional, the next property comparison is made. Convert key name OT model keys, if a mapper is provided nsstring* Jsonkeypath = Property.Name; if (keymapper) Jsonkeypath = Keymapper.modeltojsonkeyblock (Property.Name); Jmlog (@ "KeyPath:%@", Jsonkeypath); General check for data type compliance id jsonvalue = [dict Valueforkeypath:jsonkeypath]; Check for Optional properties if (Jsonvalue==nil && property.isoptional==yes) {//skip this PR Operty, continue with next property continue; }//To make a type judgment on the found value, if not JSON should returnData type is an error. (Note: Nsnull can be returned as a parameter) Class Jsonvalueclass = [Jsonvalue class]; BOOL isvalueofallowedtype = NO; For (Class Allowedtype in allowedjsontypes) {if ([Jsonvalueclass Issubclassofclass:allowedtype]) { Isvalueofallowedtype = YES; Break }} if (Isvalueofallowedtype==no) {//type not allowed Jmlog (@ "type%@ are not Allowed in JSON. ", Nsstringfromclass (Jsonvalueclass)); if (err) *err = [Jsonmodelerror errorinvaliddata]; return nil; }//check If there ' s matching property in the Model//jsonmodelclassproperty* property = CLA Ssproperties[self.classname][key]; The property's properties are then matched to the Jsonvalue type: if {///if it is a base type (int/float, etc.) direct value copy; 0) Handle Primitives if (Property.Type = = Nil && property.structname==nil) { Just copy the value [self setvalue:jsonvalue forKey:property.name]; Skip directly to the next key continue; }//If the nsnull is directly assigned null value;//0.5) handle Nils if (IsNull (Jsonvalue)) { [Self setvalue:nil forKey:property.name]; Continue }//If the value is also a Jsonmodel, recursive engage Jsonmodel//1) Check if property is itself a jsonmodel if ([[PR Operty.type class] Issubclassofclass:[jsonmodel class]) {//initialize The property ' s mode L, store it nserror* initerror = nil; ID value = [[Property.Type alloc] Initwithdictionary:jsonvalue error:&initerror]; if (!value) {if (Initerror && err) *err = [Jsonmodelerror errorinvaliddata]; return nil; } [Self SetValue:Value ForKey:property.name]; For clarity, does the same without continue continue; } else {//If there is protocol resolution in the property Jsonvalue will be parsed according to protocol, such as Nsarray<jsonmodelsubclass>,p Rotocol is Jsonmodelsubclass//2) Check if there ' a protocol to the property//) might or Not being the case there's a built in transofrm for it if (Property.protocol) { Jmlog (@ "Proto:%@", P.protocol); __transform:forproperty: function function://-First to determine whether the protocolclass in the operating environment exists, if not exist and the property is Nsarray type, direct error. Otherwise, return directly. If Protocalclass is a subclass of Jsonmodel,//If Property.Type is Nsarray// ----to determine if the conversion is used//--if the conversion is used to output a Jsonmodelarray (Nsarray) Subclass// --If the conversion is not used, the output of a nsarray, where the object is all converted to protocalclass the corresponding object/, if Property.Type is Nsdictionary ---Convert value to Protocalclass object//--by key stored in a nsdictionary output Jsonvalue = [self __transform:jsonvalue forproperty:property]; if (!jsonvalue) {if (err) *err = [Jsonmodelerror errorinvaliddata]; return nil; }}//If it is a basic JSON type (Nsstring/nsnumber)//3.1) handle matching Standard JSON Types if (property.isstandardjsontype && [Jsonvalue IsKindOfClass:property.type]) { If it is mutable, make a copy of Mutablecopy//mutable properties if (property.ismutable) {jsonvalue = [jsonvalue mutablecopy]; } Set the property value [self Setvalue:jsonvalue forKey:property.name]; Continue }//If Property.Type is Nsarray//3.3) handle values to transform If (the type does not match and Jsonvalue is not empty) or the property of the mutable (the description is a special type conversion) (![ Jsonvalue IsKindOfClass:property.type] &&!isnull (jsonvalue)) | | The property is mutable property.ismutable) { Use Jsonvaluetransformer to find the source type//searched around the Web how does this better/ /But does not find any solution, maybe that's the best idea? (hardly) Class Sourceclass = [Jsonvaluetransformer Classbyresolvingclusterclasses:[jsonvalue class]]; Jmlog (@ "to type: [%@] from type: [%@] transformer: [%@]", P.type, Sourceclass, selectorname); Use string to spell out the name string of the conversion function, go to Jsonvaluetransformer to search @sel execute the correct type//build a method selector for the property and JSON object classes nsstring* selectorname = [nsstring stringwithformat:@ "% @From%@:", (Property.structname property.structName:property.type),//target name Sourceclass]; SOURCE Name SEL selector = nsselectorfromstring (selectorname); Check if there ' s a transformer with that name if ([Valuetransformer Respondstoselector:selector]) { It's OK, believe me ... #pragma clang diagnostic push#pragma clang Diagnos Tic ignored "-warc-performselector-leaks"//transform the value Jsonvalue = [Valuetransformer PerformselecTor:selector Withobject:jsonvalue]; #pragma clang diagnostic pop [self setva Lue:jsonvalue ForKey:property.name]; } else {//it ' s not a JSON data type, and there ' s no transformer for it If property type was not Supported-that ' s a programmer mistaked-exception @throw [NSException exceptionwithname:@ "Type not Allowed" Reas On:[nsstring stringwithformat:@ "%@ type not supported for%@.%@", Property.Type, [self class], Property.Name] Userinfo:nil]; return nil; }} else {//where is not directly stored//3.4) handle "all othe R "cases (if any) [self setvalue:jsonvalue forkey:property. name]; }}}}//Last Call Validate: see if the result is valid and return without problem. Run any custom model validation nserror* ValidationError = nil; BOOL doesmodeldatavalidate = [Self validate:&validationerror]; if (doesmodeldatavalidate = = NO) {if (err) *err = ValidationError; return nil; }//model is valid! yay! return self;}
Program Highlights:
1, in order to improve efficiency through the static Nsarray and nsdictionary decoupling.
2. Jsonvaluetransformer implements a reusable type conversion template.
3, through the runtime function to resolve the property list, through the property related functions to resolve the name, and attributes information.
4, the use of Nsscanner
5. The inclusion relationship of Nsset to determine the intersection of two sets
6, using [NSObject Setvalue:forkey:] Kvo operation assignment, you can call the setter function directly, and can be assigned nil to the property
7, timely to the subclass a function can modify some behavior of the parent class
Jsonmodel Source Reading Notes