[数据存储之五]JSON文件读取

- (void)viewDidLoad {
    [super viewDidLoad];
    /*读取json*/
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"JsonFile" ofType:@"json"];
    NSData* data = [NSData dataWithContentsOfFile:filePath];
    NSJSONSerialization* json = [NSJSONSerialization JSONObjectWithData:data
                                                                options:NSJSONReadingAllowFragments
                                                                error:nil];
    NSLog(@"%@",json);
    /*写入json*/
    NSMutableDictionary* dic = [[NSMutableDictionary alloc] initWithCapacity:2];
    [dic setObject:@"zhangsan" forKey:@"name"];
    [dic setObject:[NSNumber numberWithInteger:29] forKey:@"age"];
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];
    [jsonData writeToFile:filePath atomically:YES];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
}

你可能感兴趣的:(json,数据存储)