Reputation: 1820
I've downloaded my JSON Data, but I'm having trouble accessing a specific object. From my JSON data, I'm trying to pull the most recent value
from variableName = "Elevation of reservoir water surface above datum, ft";
Here is my code:
- (void)viewWillAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSURL *url = [NSURL URLWithString:@"http://waterservices.usgs.gov/nwis/iv/?sites=02334400&period=P7D&format=json"];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if (jsonData != nil) {
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error: &error];
if (error == nil)
NSLog(@"%@", result);
}
}
Edited: It's too much data to print the output, but here is how I access the object in JS. I can't seem to write a working for statement that will do the same in Obj-C:
var d = JSON.parse(responseText);
for (var i = 0; i < d.value.timeSeries.length; i++) {
if (d.value.timeSeries[i].variable.variableName == 'Elevation of reservoir water surface above datum, ft') {
var result = d.value.timeSeries[i].values[0].value[d.value.timeSeries[i].values[0].value.length - 1];
console.log(result);
}
Upvotes: 0
Views: 1567
Reputation: 236
One thing that you may consider is using a tool to generate model classes for you. That way you can use dot accessors to make your life a little bit easier. In the Mac App Store JSON Accelerator or Objectify are pretty good options. You then pipe the NSDictionary into those model classes and it's pretty easy.
Upvotes: 0
Reputation: 38728
This is pretty ugly but it should give you something to start with:
NSArray *timeSeries = [JSON valueForKeyPath:@"value.timeSeries"];
[timeSeries enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *variableName = [obj valueForKeyPath:@"variable.variableName"];
if ([variableName isEqualToString:@"Elevation of reservoir water surface above datum, ft"]) {
NSArray *values = [obj valueForKey:@"values"];
NSDictionary *value = [values objectAtIndex:0];
values = [value objectForKey:@"value"];
value = [values lastObject];
NSLog(@"%@", [value objectForKey:@"value"]);
}
}];
Note
There is no validation/range checking of any kind I'll leave that as an exercise for you to do
Upvotes: 2