iOS:本地json文件读取、存储

// 读取本地JSON文件
- (NSArray *)readLocalFileWithName:(NSDictionary *)name {
    // 获取文件路径
            NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"json"];
    // 将文件数据化
//    NSString * path = [NSString stringWithFormat:@"/Users/admin/work/json/5012.json"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}
// 写入本地JSON文件
- (void)writJson:(NSArray*)json_dic{
    
//    NSString * filePath = [NSString stringWithFormat:@"/Users/admin/work/json/myJs.json"];
            NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/myJson.json"];
    NSData *json_data = [NSJSONSerialization dataWithJSONObject:json_dic options:NSJSONWritingPrettyPrinted error:nil];
    BOOL a =   [json_data writeToFile:filePath atomically:YES];
    if (a) {
        NSLog(@"路径:%@",filePath);
    }else {
        NSLog(@"存储失败");
    }
    
}

 

你可能感兴趣的:(iOS)