iOS - JSONModel with dynamic key

508 views Asked by At

I am calling a web service which returns dictionary to render the graph. Dictionary structure is

{"1":0,"2":0,"8":0,"9":2,"10":3,"11":0,"12":0}

The problem is keys are dynamic values like 1,2,3 etc which indicates month. Is it possible to represent this in JsonModel?

1

There are 1 answers

0
Pushkraj Lanjekar On

See you cant create properties at run time as per response structure. But we can smartly use pre-defined things and achieve this. Do following steps:

Create one model class. So your MyCustomModel.h file will look like this

#import <Foundation/Foundation.h>

@interface MyCustomModel : NSObject

@property (nonatomic, retain) NSString * myCustomKey;
@property (nonatomic, retain) NSString * myCustomValue;

@end

This will be your MyCustomModel.m file

#import "MyCustomModel.h"

@implementation MyCustomModel
@synthesize myCustomKey, myCustomValue;

-(id)init {
    self = [super init];

    myCustomKey = @"";
    myCustomValue = @"";

    return self;
}
@end

Now lets suppose {"1":0,"2":0,"8":0,"9":2,"10":3,"11":0,"12":0} is NSDictionary and lets say its name is dictionaryResponse

Now do this stuffs:

NSArray *responseKeys = [[NSArray alloc]init];
responseKeys = [dictionaryResponse allKeys];

So your responseKeys will have all keys of response like ["1","2","8","9","10","11","12",]

Now you can iterate loop and create NSMutableArray of model objects as

NSMutableArray *arrayMonthList = [[NSMutableArray alloc]init];

for (int i = 0; i < responseKeys.count; i++) {
    MyCustomModel *myModelObject = [[MyCustomModel alloc]init];
    myModelObject.myCustomKey = [NSString stringWithFormat:@"%@",[responseKeys objectAtIndex:i]];
    myModelObject.myCustomValue = [dictionaryResponse valueForKey:[NSString stringWithFormat:@"%@",[responseKeys objectAtIndex:i]]];
    [arrayMonthList addObject:myModelObject];
}

Now arrayMonthList will consist of objects of type MyCustomModel

So you can use it and parse it. Even you can use it to show on UITableView. Following code is written to print values of model properties, you can customise at your expected level.

for (int i = 0; i < arrayMonthList.count; i++) {
        MyCustomModel *myModelObject = [arrayMonthList objectAtIndex:i];
        NSLog(@"Month is %@ and its value is %@",myModelObject.myCustomKey,myModelObject.myCustomValue);
    }