【问题标题】:IOS how to replace json data using their keysIOS如何使用他们的密钥替换json数据
【发布时间】:2015-07-24 07:44:42
【问题描述】:

我想更改以下 JSON。 我的要求是我想在循环中将 ("answer": "offlinetesing") 替换为 ("answer": "test12333") 。假设如果它在索引 0 中,我只想替换索引 0 的答案。

我怎样才能做到这一点?

我正在使用此代码

NSData *data = [NSData dataWithContentsOfFile:documentFile1];
NSMutableDictionary *jsonObject1 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"jsonObject1 is %@",jsonObject1);
NSMutableArray *responsedictonary=[jsonObject1 objectForKey:@"questions"];

JSON:

{
    "currentquestion": "Define6",

    "phasecompletion": "80",
    "questions": [
        {
            "answer": "offlinetesing",
            "dmaicQuestion_ID": "Define1",
            "projectPhase": "Define"
        },
        {
            "answer": "testing",
            "dmaicQuestion_ID": "Define2",
            "projectPhase": "Define"
        }
    ],
    "questionsAnswered": 8
}

【问题讨论】:

  • 这意味着你只需要从questions标签的第一个对象中替换“answer”:“offlinetesing”??
  • 制作一个可变的 dict 副本并将“answer”设置为“whatever you want to set”

标签: ios objective-c json nsarray nsdictionary


【解决方案1】:

以下答案会对您有所帮助。

NSArray *questionArray = [jsonObject valueForKey@"questions"];

NSMutableArray *array = [NSMutableArray array];

for(NSDictionary *tempDict in questionArray){
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[tempDicr mutablecopy];
    NSString *str = [dict valueForKey:@"answer"];
    if(str isEqualToString:@"offlinetesing"){
       [dict setObject:@"test" forKey:@"answer"];
    }
    [array addObject:dict];
}

【讨论】:

  • 其崩溃的应用程序__NSDictionaryI setObject:forKey:]:无法识别的选择器发送到实例 0x7f7f6a4899e0'
  • 你必须制作该字典的可变副本
  • 好的,我试过了,但是。仍然在这里崩溃 [tempDict setObject:@"test" forKey:@"answer"];
  • @SairamGogikar 提供给你实际的逻辑,现在这是轻微的崩溃,你可以用谷歌解决它
  • 我不明白这一行 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[tempDicr mutablecopy];
猜你喜欢
  • 2017-08-07
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多