如何在NSDictionary中搜索和替换?

时间:2015-06-01 10:40:13

标签: ios objective-c nsdictionary

我有一个JSON,我转换成NSDictionary,现在我想搜索并替换其中的一些值,但我不知道如何对此,

{  
   "CODE":200,
   "APICODERESULT":"USER_INTERESTS",
   "MESSAGE":"user interests fetched successfully",
   "VALUE":{  
      "Books":[  
         {  
            "key":"7",
            "value":"Fiction",
            "selected":true
         },
         {  
            "key":"8",
            "value":"Romantic",
            "selected":true
         }
      ],
      "Music":[  
         {  
            "key":"11",
            "value":"Classical",
            "selected":false
         },
         {  
            "key":"12",
            "value":"Jazz",
            "selected":false
         },
         {  
            "key":"10",
            "value":"Pop",
            "selected":false
         },
         {  
            "key":"13",
            "value":"Western",
            "selected":false
         }
      ]
   }
}

这里我有key的值,我想在字典中搜索,当我找到具有我所拥有的值的密钥时,我想在同一个块中替换selected的值

例如: -

key的值为10,然后我想将所选键的值更改为true 所以它看起来像这样

{  
   "CODE":200,
   "APICODERESULT":"USER_INTERESTS",
   "MESSAGE":"user interests fetched successfully",
   "VALUE":{  
      "Books":[  
         {  
            "key":"7",
            "value":"Fiction",
            "selected":true
         },
         {  
            "key":"8",
            "value":"Romantic",
            "selected":true
         }
      ],
      "Music":[  
         {  
            "key":"11",
            "value":"Classical",
            "selected":false
         },
         {  
            "key":"12",
            "value":"Jazz",
            "selected":false
         },
         {  
            "key":"10",
            "value":"Pop",
            "selected":true
         },
         {  
            "key":"13",
            "value":"Western",
            "selected":false
         }
      ]
   }
}

3 个答案:

答案 0 :(得分:2)

将输入字典视为mainDictionary并使用以下代码:

NSMutableDictionary *valuesDic = [mainDictionary objectForKey:@"VALUES"];


NSArray *allPossibleKeysArray = [valuesDic allKeys];

for (int j=0; j<allPossibleKeysArray.count; j++) {

    NSString *keyStr = [allPossibleKeysArray objectAtIndex:j];

    NSArray *array = [valuesDic objectForKey:keyStr];

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

        NSMutableDictionary *dictionary = [array objectAtIndex:i];

        NSString *keyString = [NSString stringWithFormat:@"%@",[dictionary objectForKey:@"key"]];

        if([keyString isEqualToString:keyvalue]){

            [dictionary removeObjectForKey:@"selected"];
            [dictionary setObject:[NSNumber numberWithBool:true] forKey:@"selected"];
        }
    }
}

希望这会有所帮助!!

答案 1 :(得分:1)

您应该在解析JSON /将其移动到模型中时进行此类更改。以下代码是一种解决方法:

NSDictionary *initialJson = //Your JSON here
NSArray *allSubKeys= [initialJson[@"Value"] allKeys];

// Your mutable output.
NSMutableDictionary *mutableJson = [initialJson mutableCopy]

for(NSString *key in allSubKeys) {//Music && Books
    // Create another cointainer here
    for(NSArray *arr in mutableJson[@"Value][key]) {
       // Create another cointainer here           
       for(NSDictionary *dict in arr) {//key, value, selected
           for (NSString *key2 in [dict allKeys]) {
               if ([key2 isEqualToString:@"selected"] && [dict[@"value"] equals:@10]) {
                   // Save YES here
               }
               else {
                   // Just copy element
               }
               // Add object to parent container
           }
           // Add object to parent container
       }
       // Add object to parent container           
    }
    // Add object to parent container
}

答案 2 :(得分:1)

这是完整的解决方案

NSString* str=@"{\"CODE\":200,\"APICODERESULT\":\"USER_INTERESTS\",\"MESSAGE\":\"user interests fetched successfully\",\"value\":{\"Books\":[{\"key\":\"7\",\"value\":\"Fiction\",\"selected\":true},{\"key\":\"8\",\"value\":\"Romantic\",\"selected\":true}],\"Music\":[{\"key\":\"11\",\"value\":\"Classical\",\"selected\":false},{\"key\":\"12\",\"value\":\"Jazz\",\"selected\":false},{\"key\":\"10\",\"value\":\"Pop\",\"selected\":false},{\"key\":\"13\",\"value\":\"Western\",\"selected\":false}]}}";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSLog(@"dictionary before updating: %@", dictionary);
    // copy old dict
    NSMutableDictionary* newDict=[[[NSMutableDictionary alloc]init]autorelease];
    [newDict addEntriesFromDictionary:dictionary];
    // get the entry to be changed
    NSMutableDictionary* valueDict=[[[NSMutableDictionary alloc]init]autorelease];
    [valueDict addEntriesFromDictionary:newDict[@"value"]];
    NSMutableArray* musicArray=[[[NSMutableArray alloc] init] autorelease];
    [musicArray addObjectsFromArray:newDict[@"value"][@"Music"]];
    // get the music array and change your property
    NSMutableDictionary* musicDict2=[[[NSMutableDictionary alloc] init] autorelease];
    [musicDict2 addEntriesFromDictionary:[musicArray objectAtIndex:2]];
    [musicDict2 setValue:[NSNumber numberWithBool:YES] forKey:@"selected"];
    [musicArray replaceObjectAtIndex:2 withObject:musicDict2];
    // update the value dictionary
    [valueDict setObject:musicArray forKey:@"Music"];
    //update the new dictionary
    [newDict setObject:valueDict forKey:@"value"];
    NSLog(@"dictionary after updating: %@", newDict);