【问题标题】:how to search and replace in NSDictionary?如何在 NSDictionary 中搜索和替换?
【发布时间】:2015-06-01 10:40:12
【问题描述】:

我有一个转换为 NSDictionary 的 JSON,现在我想搜索并替换其中的一些值,但我不知道如何做到这一点,

{  
   "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
         }
      ]
   }
}

【问题讨论】:

  • 一行一行的庞大 JSON 并不能帮助我们理解您想要什么。我一直滚动大约 5 次,但我仍然无法发现差异。说明您想要什么和/或发布一个最小示例来展示您的需求。
  • 请使用jsonformatter.curiousconcept.com 格式化 json,因为我无法用那个巨大的 json 发布问题
  • 不,我不会。你了解“最小”这个词吗? 减小 JSON 的大小,以便只保留相关部分。

标签: ios objective-c nsdictionary


【解决方案1】:

将您的输入字典视为 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"];
        }
    }
}

希望这会有所帮助!

【讨论】:

  • bookArray 不会返回可变字典,但 NSDictionary
  • 但是我没有 Books 的值,我想这样做,而这个 Book 不是固定的,它可以是其他任何东西,我所拥有的只是 key 的值,例如 10、11 , 15 等等,这些都是独一无二的。
  • @Varun 我已经更新了答案,请检查。希望这就是你要找的东西
  • 我认为它应该可以工作,但不知道为什么
  • 最后一行会报错:-[__NSDictionaryI setObject:forKey]: unrecognized selector sent to instance
【解决方案2】:

您应该在解析 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
}

【讨论】:

  • 谢谢我解决了这个问题。
  • 我修复了很多类型错误,现在检查会尽快回复您
  • for (NSString *key2 in [dict allKeys]) { 这里 dict 仅包含 @"selected" 并且此时应用程序正在崩溃
【解决方案3】:

这里是完整的解决方案

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

【讨论】:

  • 我已经告诉过我没有Music 的值,它是动态的,可以根据网络服务进行更改
  • okz.. 但是你可以通过添加动态字符串而不是音乐来使其动态
  • 但是如果我不知道会发生什么,我怎么能得到那个动态字符串呢?
  • varun 你必须确定一些值,比如在 torap 中回答它的键值
猜你喜欢
  • 2017-01-05
  • 2014-02-03
  • 2020-08-09
  • 1970-01-01
  • 2010-12-13
  • 2015-08-18
  • 2010-10-06
  • 2011-09-08
  • 1970-01-01
相关资源
最近更新 更多