Reputation: 128
I'm trying to check if a value in my .json file is "0" or "1".
My .json file:
{
"timetable": [
{
"50mhour": "1",
"on": "1"
},
{
"50hour": "2",
"on": "1"
},
{
"50hour": "50min1",
"on": "1"
},
{
"techhour": "4",
"on": "1"
},
]
}
I created a method to call this URL:
-(void)makeRequests
{
NSURL *url = [NSURL URLWithString:@"http://content.app.ch/api/timetable.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject)
{
self.get = [responseObject objectForKey:@"timetable"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject)
{
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
}
And ofcourse, I created a NSDictionary as well
NSDictionary *tempDictionary= [self.get objectAtIndex:1];
I'm not quite sure about the objectAtIndex
value.
What is the right way to check if a value is "0" or "1" I know isEqualToString:
can probably do this but I'm not sure how.
UPDATE: Tried this as a suggestion from the answers below:
NSNumber *obj = [[self.get objectAtIndex:0] objectForKey:@"on"];
int onValue = [obj intValue];
if (onValue == 1) {
NSLog(@"works!");
}
else {
NSLog(@"doesn't work!");
}
The code works, but the JSON value is "1" and the NSlog still shows "doesn't work!".
Upvotes: 0
Views: 161
Reputation: 3815
The flow of your JSON is like this:
You have the array in JSON and in that array, the first element is dictionary.
You first get the data from JSON directly into an array. Then get the first object of Array into dictionary and then get the value like this
Get the value for On from this code :
int on = [[[self.get objectAtIndex:0] objectForKey:@"on"] integerValue];
int value = [[[self.get objectAtIndex:0] objectForKey@"50hour"] integerValue]
Upvotes: 0
Reputation: 8147
The JSON-encoded array you presented (timetable) has only one element, so taking objectAtIndex:1
would crash your program/throw an out of bounds exception. Get element 0 or lastObject
from the array and you'll have a pointer to the following dictionary:
{
"50hour": "1",
"on": "1"
}
Since this is a dictionary, the correct way to look up a value is by key:
NSNumber *obj = [[self.get objectAtIndex:0] objectForKey:@"on"]; // or @"50hour", whichever you need
int onValue = [obj intValue];
Upvotes: 1