0

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?

V V
  • 774
  • 1
  • 9
  • 29
  • 2
    The issue is actually more that Objective-C doesn't allow properties to have names that are numbers (or even anything that begins with a digit). But what's you can definitely manipulate dictionaries derived from JSON without JsonModel, just use `NSJSONSerialization JSONObjectWithData:options:error:` and access keys in the returned `NSDictionary`. – jcaron Dec 27 '16 at 23:58
  • What is your expected output – Bista Dec 28 '16 at 05:47

1 Answers1

0

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);
    }
Pushkraj Lanjekar
  • 2,254
  • 1
  • 21
  • 34