-1

I'm currently using JSONModel by icanzilb to parse my JSON structures obtained online. The issue is that I have a dictionary which has numeric keys, plus these numeric keys are generated by the server on-demand. So theoretically I have no advance knowledge of what these numeric keys will be. So under this situation, I couldn't add a @property to my JSON data header files.

Any idea on how to deal with this situation?

An example of the JSON structure:

{
 "Content":[
             {
              "0":{...},
              "1":{...},
              "2":{...},
              "Forum":"1",
              "Member": "Michael",
             }
          ],
 "Count":"5"
}
Marcus
  • 548
  • 1
  • 5
  • 13

2 Answers2

1

You can't add properties to a native object dynamically based on the JSON response but you could have a property that is a NSMutableDictionary and fill that with only the numeric keys/objects that are dynamic.

-(void)fillMyDictionaryProperty {

    NSCharacterSet *nonNumericSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];


    for (NSString *key in jsonDictionary.allKeys) {

        if ([key rangeOfCharacterFromSet:nonNumericSet].location == NSNotFound) {

            id object = [jsonDictionary objectForKey:key];
            [myMutableDictionary setObject:object forKey:key];

        }

    }

}

Then you could use this to get the object associated with that key

-(id)getPropertyWithNumber:(NSInteger)num {

    NSString *key = [NSString stringWithFormat:@"%li", (long)num];
    return [myMutableDictionary objectForKey:key];

}
Zigglzworth
  • 6,645
  • 9
  • 68
  • 107
0

First get the dictionary in Content array. Then get the count of dictionary, you know that all the pairs in the dictionary have numerical key values except last two. you can get the count of numerical values as follows.

NSArray *array = [jsonString valueForKey:@"Content"];
NSDictionary *dict = [array objectAtIndex:0];

//Count of numeric keys in dict

int count = [dict count]-2;

After that you can get all the numeric key values in a loop.

for(int i=0;i<count;i++) 
{

    NSDictionary *valueDict = [dict valueForKey:[NSString stringWithFormat:@"%d",i]];
}
Fawad Masud
  • 12,219
  • 3
  • 25
  • 34
  • Thanks for the quick reply. However, the issue here is that the "0", "1"... are generated by server on-demand. So there could be instances where there is only "0" and "1" or instances where there is "0", "1", "2", "3"..."100". So I can't hard code them in, right? – Marcus Jan 26 '15 at 08:44
  • Yes you cannot hardcode them. It totally depends on the server response. – Fawad Masud Jan 26 '15 at 08:47
  • Thanks Fawad. This is the method I use before I switch to using the JSONModel library, which if to serve its purpose of providing convenience in parsing, do not make sense doing the above. Thanks for the effort by the way! – Marcus Jan 26 '15 at 11:16