ios - 如何将 JSON 数据保存到 iPhone

标签 ios json sqlite nsdictionary nsdata

我有一个 json 数据来显示一些信息.. 但我应该生成“一个文件”以将这些信息保存到我的 iPhone。想法?

- (void)showInfos {
NSMutableDictionary *infoDictionary = [[NSMutableDictionary alloc]init];
[infoDictionary setObject:self.totalDuration.text forKey:@"totalFrames"];

NSMutableArray *nodesArray = [[NSMutableArray alloc]init];
[nodesArray addObject:@{@"x":@(_zeroButton.frame.origin.x),@"y":@(_zeroButton.frame.origin.y),@"frame":self.zeroBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_firstButton.frame.origin.x),@"y":@(_firstButton.frame.origin.y),@"frame":self.firstBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_secondButton.frame.origin.x),@"y":@(_secondButton.frame.origin.y),@"frame":self.secondBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_thirdButton.frame.origin.x),@"y":@(_thirdButton.frame.origin.y),@"frame":self.thirdBtnLbl.text}];
[nodesArray addObject:@{@"x":@(_fourthButton.frame.origin.x),@"y":@(_fourthButton.frame.origin.y),@"frame":self.fourthBtnLbl.text}];
[infoDictionary setObject:nodesArray forKey:@"nodes"];

NSLog(@"dicArray:%@",infoDictionary);
NSData *data = [NSJSONSerialization dataWithJSONObject:infoDictionary options:kNilOptions error:nil];
NSArray *retDicArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"retDicArray:%@",retDicArray);
}

最佳答案

您可以使用 writeToFile:atomically: 将该数据写入文件NSData 的方法。

NSData *data       = [NSJSONSerialization dataWithJSONObject:infoDictionary options:kNilOptions error:nil];
NSString *docDir   = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"MyJSONFile.json"];
[data writeToFile:filePath atomically:YES];

关于ios - 如何将 JSON 数据保存到 iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33473358/

相关文章:

android - 通知 iOS 和 Android 服务器上的数据更改

ios - 在 Objective C 中创建负数数组

.net - Entity Framework Core 连接管理

objective-c - iOS 中的 Sqlite 数据库似乎是从用户目录加载的,但文件与应用程序中的不同

android - 有没有办法在 Android 平台的 SQlite 中实现全文搜索(FTS)?

iOS:在 NSAttributedString 上添加按钮

java - 安卓 : getParams() called two times dont know why?

json - 在 oracle 12c 中以 JSON 形式返回 sql 查询的结果

python - 解析 JSON 时处理 KeyError

iphone - 如何在 ios5 中播放 AVAudioPlayer 本地方法?