Search code examples
iosjsonmodel

iOS JSONModel check for class


I need to check during parsing data from json file if there will be NSArray or NSDictionary model because bug on server side. If there is Array I need to ignore this model.

@property (strong, nonatomic) NSDictionary <Optional,RCTruckInningsModel> *innings;

+(BOOL)propertyIsOptional:(NSString*)propertyName
{
return YES;
}

I use jsnomodel.com

This is not working

Thanks


Solution

  • You are correctly defining "innings" as Optional, but this is not how Optional works. Properties defined as Optional can be either their specified type or nil.

    You have a very non-standard situation on your hands and it will require a special solution. Off top of my head you can do the following:

    1) define an ignored property (i.e. JSONModel does not process it when importing JSON)

    @property (strong, nonatomic) NSDictionary<Ignore>* innings;
    

    2) then import the property value yourself by overriding initWithDictionary (in case you use initWithDictionary):

    -(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
    {
      self = [super initWithDictionary:dict error:err];
      if (self) {
        if ([dict[@"innings"] isKindOfClass:[NSDictionary class]]) {
          NSDictionary* d = dict[@"innings"];
          NSMutableDictionary* md = [@{} mutableCopy];
          for (NSString* key in d.allKeys) {
            RCTruckInningsModel* model = [[RCTruckInningsModel alloc] initWithDictionary: d[key]];
            if (model) {
              md[key] = model;
            }        
          }
          self.innings = [md copy];
        }
      }
      return self;
    }
    

    I didn't actually try the code in Xcode, but that's what I think the general solution should be - you'll need to try it yourself and finish it up for your own JSON structure, etc. But it should push you in the right direction

    Accept the answer if it helps you to solve your problem