JSON

JSONModelÔ´ÂëÔĶÁ±Ê¼Ç

×ÖºÅ+ ×÷ÕߣºH5Ö®¼Ò À´Ô´£ºH5Ö®¼Ò 2017-02-08 09:06 ÎÒÒªÆÀÂÛ( )

JSONModelÔ´ÂëÔĶÁ±Ê¼Ç,JSONModelÊÇÒ»¸ö½âÎö·þÎñÆ÷·µ»ØµÄJsonÊý¾ÝµÄ¿â¡£Í¨³£·þÎñÆ÷´«»ØµÄjsonÊý¾ÝҪͨ¹ýдһ¸öÊý¾Ýת»»Ä£¿é½«NSDictionaryת»»ÎªModel£¬½«NSStri

ÕýÎÄ

JSONModelÊÇÒ»¸ö½âÎö·þÎñÆ÷·µ»ØµÄJsonÊý¾ÝµÄ¿â¡£

ͨ³£·þÎñÆ÷´«»ØµÄjsonÊý¾ÝҪͨ¹ýдһ¸öÊý¾Ýת»»Ä£¿é½«NSDictionaryת»»ÎªModel£¬½«NSStringÊý¾Ýת»»ÎªModelÖÐpropertyµÄÊý¾ÝÀàÐÍ¡£

ÕâÑù·þÎñÆ÷Èç¹ûÒª×öÐ޸ģ¬¿ÉÄÜÐèÒª¸ÄÁ½Èý¸öÎļþ¡£

JSONModelµÄ³öÏÖ¾ÍÊÇΪÁ˽«ÕâÖÖ½âÎö¹¤×÷ÔÚÉè¼Æ²ãÃæÍê³É¡£

ʹÓ÷½·¨£º²Î¿¼Á¬½Ó

¶ÔÆäÔ´ÂëµÄºËÐIJ¿·ÖJSONModel.m×öÁËÔ´ÂëÔĶÁ£¬±Ê¼ÇÈçÏ£º
ÔÚ
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
º¯ÊýÖÐÍê³ÉËùÓнâÎö¹¤×÷£ºÈç¹ûÓÐÈκÎʧÎó»òÕß´íÎóÖ±½Ó·µ»Ønil¡£

-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err { //1¡¢×öÓÐЧÐÔÅжϣ¨dictÊDz»ÊÇ¿Õ°¡£¬dictÊDz»ÊÇÕæÊÇÒ»¸ö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; } //__setup__ÖÐͨ¹ýµ÷ÓÃ__restrospectProperties½¨Á¢ÀàÊôÐÔµÄÓ³Éä±í£¬²¢ÇÒ´æ·ÅÔÚÈ«¾Ö±äÁ¿classPropertiesÀïÃæ //->__restrospectPropertiesÖÐÀûÓÃruntime function¸ã³öÊôÐÔÁÐ±í£º // ->»ñµÃÊôÐÔÁбíclass_copyPropertyList(µÃµ½objc_property_tÊý×é)->¶ÔÓÚÿһ¸öobjc_property_tµ÷ÓÃproperty_getName»ñµÃÃû³Æ£¬property_getAttributes»ñµÃÊôÐÔµÄÃèÊö£¨×Ö·û´®£©->ͨ¹ý½âÎö×Ö·û´®»ñµÃÊôÐÔµÄÀàÐÍ¡¢ÊÇ·ñÊÇMutable¡¢ÊÇ·ñÊÇ»ù±¾µÄJSONÀàÐÍµÈµÈ // ->µ÷ÓÃ[class superclass]»ñµÃ¸¸Àà¼ÌÐø»ñÈ¡Áбí // ->ÁÐ±í±£´æÔÚclassPropertiesÖб¸Óà //->µ÷ÓÃ+keyMapper»ñµÃkeyת»»ÁÐ±í£¬Éú³ÉJSONKeyMapper¶ÔÏó´æÈëkeyMapper¡£ //do initial class setup, retrospec properties [self __setup__]; //¿´¿´±Ø´«²ÎÊýÖÐÊÇ·ñÔÚÊäÈë²ÎÊýÖж¼ÓС£ //check if all required properties are 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) { //¶Ô±ÈdictÊäÈëµÄkeyNameµ¼ÈëNSSetÓëkeyMapperÖÐJSONKeyMapper¶ÔÏó×ökeyNameµÄת»»¡£Í³Ò»×ª»»Îª¶ÔÏóµÄ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 = transformedIncomingKeys; } //ÀûÓÃNSSetµÄisSubsetOfSet:½«±Ø´«²ÎÊý±íÓëÊäÈëµÄkeyName±í¶Ô±È¡£Èç¹û²»ÊÇ°üº¬¹Øϵ˵Ã÷²ÎÊý´«µÄ²»¹»¡£ //check for missing input keys if (![requiredProperties isSubsetOfSet:incomingKeys]) { //get a list of the missing properties [requiredProperties minusSet:incomingKeys]; //not all required properties are 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; //´Ó¶ÔÏóµÄclassPropertiesÁбíÖÐÑ­»·µ½dictÖÐÈ¡Öµ£º£¨¸³ÖµÊ¹ÓÃKVO²Ù×÷µÄsetValue:forKey:À´×öµÄ£¬ÕâÑù»áÖ±½Óµ÷ÓÃsetterº¯Êý¸³Öµ£© //loop over the incoming keys and set self's properties for (JSONModelClassProperty* property in [self __properties__]) { //¶ÔÓÚÿһ¸ö¶ÔÏóµÄproperty£¬Í¨¹ýkeyMapperµÄת»»ÕÒµ½¶ÔÓ¦dict propertyµÄdictKeyPath£¬ÕÒµ½ÖµjsonValue¡£Èç¹ûûÓÐÖµ£¬²¢ÇÒÕâ¸öÊôÐÔÊÇOptionalµÄ¾Í½øÐÐÏÂÒ»Ïîproperty¶Ô±È¡£ //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 property, continue with next property continue; } //¶ÔÕÒµ½µÄÖµ×öÀàÐÍÅжϣ¬Èç¹û²»ÊÇJSONÓ¦¸Ã·µ»ØµÄÊý¾ÝÀàÐ;ͱ¨´í¡££¨×¢Ò⣺NSNullÊÇ¿ÉÒÔ×÷Ϊ²ÎÊý»Ø´«µÄ£© 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 %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)); if (err) *err = [JSONModelError errorInvalidData]; return nil; } //check if there's matching property in the model //JSONModelClassProperty* property = classProperties[self.className][key]; //½Ó×ŶÔpropertyµÄÊôÐÔÓëjsonValue½øÐÐÀàÐÍÆ¥Å䣺 if (property) { //Èç¹ûÊÇ»ù±¾ÀàÐÍ£¨int/floatµÈ£©Ö±½ÓÖµ¿½±´£» // 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; } //Èç¹ûÊÇNSNullÖ±½Ó¸³¿ÕÖµ£» // 0.5) handle nils if (isNull(jsonValue)) { [self setValue:nil forKey: property.name]; continue; } //Èç¹ûÊÇÖµÒ²ÊÇÒ»¸öJsonModel£¬µÝ¹é¸ãJsonModel // 1) check if property is itself a JSONModel if ([[property.type class] isSubclassOfClass:[JSONModel class]]) { //initialize the property's model, 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 { //Èç¹ûpropertyÖÐÓÐprotocol½âÎö½«jsonValue°´ÕÕprotocol½âÎö£¬ÈçNSArray<JsonModelSubclass>£¬protocol¾ÍÊÇJsonModelSubclass // 2) check if there's a protocol to the property // ) might or not be the case there's a built in transofrm for it if (property.protocol) { //JMLog(@"proto: %@", p.protocol); //__transform:forProperty:º¯Êý¹¦ÄÜ£º // ->ÏÈÅжÏÏÂprotocolClassÊÇ·ñÔÚÔËÐл·¾³ÖдæÔÚ£¬Èç²»´æÔÚ²¢ÇÒpropertyÊÇNSArrayÀàÐÍ£¬Ö±½Ó±¨´í¡£·ñÔò£¬Ö±½Ó·µ»Ø¡£ // ->Èç¹ûprotocalClassÊÇJsonModelµÄ×ÓÀ࣬ // ->Èç¹ûproperty.typeÊÇNSArray // ->ÅжÏÒ»ÏÂÊÇ·ñÊÇʹÓÃʱת»» // ->Èç¹ûΪʹÓÃʱת»»ÔòÊä³öÒ»¸öJSONModelArray(NSArray)µÄ×ÓÀà // ->Èç¹û²»ÊÇʹÓÃʱת»»ÔòÊä³öÒ»¸öNSArray£¬ÆäÖеĶÔÏóÈ«²¿×ª»»ÎªprotocalClassËù¶ÔÓ¦¶ÔÏó // ->Èç¹ûproperty.typeÊÇNSDictionary // ->½«valueת»»ÎªprotocalClassËù¶ÔÓ¦¶ÔÏó // ->¸ù¾Ýkey´æ´¢µ½Ò»¸öNSDictionaryÖÐÊä³ö jsonValue = [self __transform:jsonValue forProperty:property]; if (!jsonValue) { if (err) *err = [JSONModelError errorInvalidData]; return nil; } } //Èç¹ûÊÇ»ù±¾JSONÀàÐÍ£¨NSString/NSNumber£© // 3.1) handle matching standard JSON types if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) { //Èç¹ûÊÇmutableµÄ£¬×öÒ»·ÝMutableCopy //mutable properties if (property.isMutable) { jsonValue = [jsonValue mutableCopy]; } //set the property value [self setValue:jsonValue forKey: property.name]; continue; } //Èç¹ûproperty.typeÊÇNSArray // 3.3) handle values to transform if ( //Èç¹û£¨ÀàÐÍûÓÐÆ¥Å䣬²¢ÇÒjsonValue²»Îª¿Õ£©»òÕßÊÇMutableµÄproperty£¨ËµÃ÷ÊÇÌØÊâÀàÐÍת»»£© (![jsonValue isKindOfClass:property.type] && !isNull(jsonValue)) || //the property is mutable property.isMutable ) { //ÀûÓÃJSONValueTransformerÕÒµ½Ô´ÀàÐÍ // searched around the web how to do this better // but did 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); //ÓÃ×Ö·û´®Æ´³öת»»º¯ÊýµÄÃû³Æ×Ö·û´®£¬µ½JSONValueTransformerÖÐÈ¥ËÑË÷@SELÖ´ÐгöÕýÈ·ÀàÐÍ //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 diagnostic ignored "-Warc-performSelector-leaks" //transform the value jsonValue = [valueTransformer performSelector:selector withObject:jsonValue]; #pragma clang diagnostic pop [self setValue:jsonValue forKey: property.name]; } else { // it's not a JSON data type, and there's no transformer for it // if property type is not supported - that's a programmer mistaked -> exception @throw [NSException exceptionWithName:@"Type not allowed" reason:[NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name] userInfo:nil]; return nil; } } else { //ÄĶù¶¼²»ÊǵÄÖ±½Ó´æÆðÀ´ // 3.4) handle "all other" cases (if any) [self setValue:jsonValue forKey: property.name]; } } } } //×îºóµ÷ÓÃvalidate:¿´¿´½á¹ûÊDz»ÊÇÓÐЧ£¬Ã»ÎÊÌâ¾Í·µ»ØÁË¡£ //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; }

¡¡

1.±¾Õ¾×ñÑ­ÐÐÒµ¹æ·¶£¬ÈκÎתÔصĸå¼þ¶¼»áÃ÷È·±ê×¢×÷ÕߺÍÀ´Ô´£»2.±¾Õ¾µÄÔ­´´ÎÄÕ£¬ÇëתÔØʱÎñ±Ø×¢Ã÷ÎÄÕÂ×÷ÕߺÍÀ´Ô´£¬²»×ðÖØÔ­´´µÄÐÐΪÎÒÃǽ«×·¾¿ÔðÈΣ»3.×÷ÕßͶ¸å¿ÉÄܻᾭÎÒÃDZ༭Ð޸Ļò²¹³ä¡£

Ïà¹ØÎÄÕÂ
  • hibernateÕûºÏ¿ª·¢Àý×Ó

    hibernateÕûºÏ¿ª·¢Àý×Ó

    2017-02-08 10:07

  • ReactNativeÖ®package.jsonÎļþÏê½â

    ReactNativeÖ®package.jsonÎļþÏê½â

    2017-02-08 08:01

  • .NetCore Json´úÌæÁËXml

    .NetCore Json´úÌæÁËXml

    2017-02-07 18:05

  • PHP¸ñʽ»¯jsonÊý¾ÝµÄʵÀý

    PHP¸ñʽ»¯jsonÊý¾ÝµÄʵÀý

    2017-02-06 15:06

ÍøÓѵãÆÀ
¸