Reputation: 4055
I am trying to wrap my head around pulling a keys value from a JSON array and saving it as a String for comparison later: The following code makes my app crash when it gets to this section of code. I don't understand why.
My json array looks like so:
[{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"}]
My xcode:
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
NSDictionary* userType = [userarray_login objectForKey:@"User_Name"];
NSString *userPermission = [userType objectAtIndex:0];
if ([userPermission isEqualToString:@"jbliz"])
{
NSLog(@"I should get the avalue here: %@", userPermission);
}
I am confused between NSDictionary and NSString. Any feedback would be a
Upvotes: 1
Views: 1277
Reputation: 7789
Your json has array of Dictionary you need to follow below steps,
//NSJSONSerialization return you array in userarray_login
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
//You fetch Dictionary from the array
NSDictionary* userType = [userarray_login objectAtIndex:0];
//Fetch NSString value using keyValue
NSString *userPermission = [userType objectForKey:@"User_Name"];
//String comparison
if ([userPermission isEqualToString:@"jbliz"])
{
NSLog(@"I should get the avalue here: %@", userPermission);
}
This is correct code for your stuff.
Upvotes: 1
Reputation: 1210
Json Array : [{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"},{},...]
an array contains Dictionaries.
for this try like,
NSArray * userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
for (NSDictionary * dict in userarray_login) {
NSString * name = [dict objectForKey:@"User_Name"];
if ([name isEqualToString:@"jbliz"]) {
NSLog(@"Value is here: %@", name);
}
}
Upvotes: 1
Reputation: 3289
NSMutableArray *name=[[[NSMutableArray alloc] initWithArray:[userarray_login valueForKey:@"User_Name"]]retain];
// Get the only all Names into name Array from json Array
NSString *userPermission = [name objectAtIndex:0]; // get the first name from Array
if ([userPermission isEqualToString:@"jbliz"])
{
NSLog(@"I should get the avalue here: %@", userPermission);
}
Upvotes: 1