在JSON文件中添加和删除数据

时间:2014-06-28 11:04:21

标签: ios objective-c json nsdata nsjsonserialization

我在项目中添加了Objects.json文件,其中包含以下代码:

{
"circle": [
       [1, 3], [2, 1], [3, 2],
],
"line": [
       [2, 1], [3, 2], [1, 3],
],
"A_Letter": [
       [3, 3], [2, 1], [1, 2],
    ],
}

如何在此文件中添加新密钥?

例如,如果我想删除“line”键,怎么办呢?

2 个答案:

答案 0 :(得分:2)

尝试这可能会有所帮助,在此我解决JSON并删除你想要的密钥..

 NSString *str = @"{\"circle\": [       [1, 3], [2, 1], [3, 2],],\"line\": [       [2, 1], [3, 2], [1, 3],],\"A_Letter\": [       [3, 3], [2, 1], [1, 2],    ]}";
  NSMutableDictionary *datadic = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
  [datadic removeObjectForKey:@"line"];
 NSLog(@"data return %@",datadic);

谢谢

答案 1 :(得分:0)

因为这是字典数组。因此,要添加到字典中,请使用setObject:ForKey:方法并删除使用removeObjectForKey:如下所示: -

 NSMutableDictionary *mutDict=[yourjsonDict mutableCopy];
 [mutDict setObject: @[@[1,2],@[2,3]] forKey:@"yourKey"];

  // now for removing 
  [mutDict removeObjectForKey:@"line"];