KMR
KMR

Reputation: 305

How should I parse array of array of object in Objective C using JSONModel?

I have a json object which contains array of array of object. I need to parse it using JSONModel.

Eg of json:

    {
      "object": [
        [
          {
            "a": 1,
            "b": 2
          },
          {
            "c": 1,
            "d": 4
          }
        ],
        [
          {
            "a": 3,
            "b": 6
          },
          {
            "e": 2,
            "f": 3
          }
        ]
      ]
    }

How should I declare it in my JSONModel? Declaring like this is giving me as NSArray of NSDictionary.

    @interface SomeClass : JSONModel

    @property (nonatomic, retain) NSArray<NSArray<AphabetJsonModelClass> *> *object;

    @end

Upvotes: 2

Views: 325

Answers (1)

yxjxx
yxjxx

Reputation: 21

Your should use custom getter/setter like this.

@interface SomeClass : JSONModel
@property (nonatomic, copy) NSArray<Optional> *object;// NSArray<ABPlusCDModel *> * 

@end

@implementation SomeClass
- (void)setObjectWithNSArray:(NSArray *)array {
    NSMutableArray *list = [NSMutableArray arrayWithCapacity:array.count];
    [array enumerateObjectsUsingBlock:^(NSArray *obj, NSUInteger idx, BOOL *stop) {
        if (![obj isKindOfClass:[NSArray class]]) {
            return;
        }

        NSMutableArray *l = [NSMutableArray arrayWithCapacity:obj.count];
        [obj enumerateObjectsUsingBlock:^(NSDictionary *o, NSUInteger idx, BOOL *stop) {
            ABPlusCDModel *m = [[ABPlusCDModel alloc] initWithDictionary:o error:nil];
            if (m) {
                [l addObject:m];
            }
        }];

        [list addObject:l.copy];
    }];

    self.object = list;
}

- (NSArray *)JSONObjectForObject {
    NSMutableArray *list = [NSMutableArray arrayWithCapacity:self.object.count];
    [self.group enumerateObjectsUsingBlock:^(NSArray *a, NSUInteger idx, BOOL *stop) {
        NSMutableArray *l = [NSMutableArray arrayWithCapacity:a.count];
        [a enumerateObjectsUsingBlock:^(ABPlusCDModel *o, NSUInteger idx, BOOL *stop) {
            [l addObject:o.toDictionary];
        }];
        [list addObject:l];
    }];
    return list.copy;
}

Upvotes: 1

Related Questions