简体   繁体   中英

How to retrieve data from local file of json to a dictionary in Objective C iOS

I have trouble in retrieving the data from my JSON file to a dictionary and then I will access the values inside array of that dictionary to take the time and compare the time what I have done so far is that.

Note: I have multiple timings for one month.

in my viewDidLoad I have defined

- (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);

saving data in dictionary

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

in my console I get all the data from my json and my json look like this

{
 "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)"
  }
}
]
}

You should do like this way, where Palettes.json is a local file.

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

Let me know if there is any query.

UPDATE

According to your Output of JSON, you will get data array like this,

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

You can iterate through data array to get timings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM