ios - 如何从 json 的本地文件检索数据到 Objective C iOS 中的字典

标签 ios objective-c arrays json nsdictionary

我在将数据从我的 JSON 文件检索到字典时遇到问题,然后我将访问该字典数组中的值来花时间比较我到目前为止所做的时间就是这样。

注意:我一个月有多个时间。

在我的 viewDidLoad 中我定义了

- (void)viewDidLoad {
[super viewDidLoad];

NSURL *url = [NSURL fileURLWithPath:@"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Json data is here %@", fileContent);

在字典中保存数据

    NSArray *data = [[theFeedString JSONValue] objectForKey:@"data"];
for (NSDictionray *dict in data) {
    NSString *timings = [[dict objectForKey:@"timings"] intValue];
}

在我的控制台中,我从我的 json 中获取所有数据,我的 json 看起来像这样

{
 "data": [
{
  "timings": {
    "Sunrise": "07:14 (PKT)",
    "Sunset": "18:15 (PKT)",
    "Midnight": "00:45 (PKT)"
  }
},
{
  "timings": {
    "Sunrise": "07:13 (PKT)",
    "Sunset": "06:40 (PKT)",
    "Midnight": "00:45 (PKT)"
  }
}
]
}

最佳答案

你应该这样做,其中 Palettes.json 是一个本地文件。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Palettes" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

如果有任何疑问,请告诉我。

更新

根据你的JSON输出,你会得到这样的数据数组,

NSArray *data = json["data"];
[data enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
    NSDictionary *timings = object["timings"];
    NSString *sunrise = timings["Sunrise"];
}];

您可以遍历数据数组以获取时间

关于ios - 如何从 json 的本地文件检索数据到 Objective C iOS 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49405722/

相关文章:

javascript - 将数组动态映射到嵌套对象

jQuery:如何循环多维数组

javascript - 使用数组作为哈希表

ios - 在 UITableViewCell 中动态调整 UILabel?

iphone - UIPickerView 设置选中

ios - 动态将UIButton添加到UITableViewCell错误

ios - 在 iOS 上使用 google api 获取 json 数据时遇到问题

iphone - 线程 1 : Program received signal: "EXC_BAD_ACCESS"

ios - 从自定义 UITableViewCell 中的按钮执行 segue

ios - 在 MKMapView 上设置多个引脚,并让 Callout View 显示正确的信息?