Reputation: 205
I can't figure why i don't get the values from the json.
{"user_id":"150","user_name":"Example","user_lastname":"Ex"}
I use this code:
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *dictionary in array)
{
if([dictionary isEqual:@"user_id"]){
self.userId = [dictionary valueForKey:@"user_id"];
}
Thanks for helping.
Upvotes: 1
Views: 84
Reputation: 49710
issue with your if condition is wrong in to for loop is that JSON
dictionary in to array then you code is correct just need to change if condition as bellow else if only one data in to your JSON
response you can fetch directly in to dictionary and set direct keyvalue
of string:-
if([dictionary valueForKey:@"user_id"])
{
self.userId = [dictionary valueForKey:@"user_id"];
}
Upvotes: 1
Reputation: 9144
By doing this :
if([dictionary isEqual:@"user_id"])
You are comparing a nsdictionary with a nsstring so it will always return false. If the json you show is the full json string then, it is an nsdictionary at first and you don't need to loop over.
Try this instead :
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *user_id = [dictionary valueForKey:@"user_id"]
if(user_id){
self.userId = user_id;
}
Upvotes: 2
Reputation: 10424
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
self.userId = [dictionary valueForKey:@"user_id"];
try this. Your JSON representation already say it is dictionary (ie {} stands for dictionary)
Upvotes: 2
Reputation: 119021
The JSON you show is a dictionary, not an array of dictionaries. So your code is looping over the dictionary keys.
If in doubt, log the class of the object you get fromNSJSONSerialization
to verify.
You should also be checking & logging any error returned from the deserialisation. And you should be considering the logic of trying to compare a dictionary with a string.
Upvotes: 1