iOS:使用JSONModel,如何抓住和数字键字典吗? - iOS: Using JSONModel, how do you grab dictionaries with numeric key?

- 此内容更新于:2015-12-13



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:

              "Member": "Michael",

(原文:Why are you using dynamic keys ?)


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];


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]];

(原文: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?)


(原文:Yes you cannot hardcode them. It totally depends on the server response.)


(原文:Sorry I understand your problem now. Please check update.)


(原文: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!)