Adding 2 keyvalues to list from JSON object
I want to append 2 key values from JSON object to my list in开发者_开发百科 iPhone app. Below is my code for that,
SBJsonParser *jsonParser = [[[SBJsonParser alloc] init] autorelease];
NSString *jsonString=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://test/json/json_data.php"]];
id response = [jsonParser objectWithString:jsonString error:NULL];
NSDictionary *feed = (NSDictionary *)response;
list = (NSArray *)[feed valueForKey:@"fname"];
the above code properly displays the value from fname but what do i do if i want to add lname to it. for eg, my object is [{"fname":"Bill","lname":"Jones"},{"fname":"John","lname":"Jacobs"}] i want to display names as Bill Jones, John Jacobs and so on in the list. Currently it only displays Bill, John..I tried doing something like @"fname"@lname but it wont work..Can anybody please help me..
An observation: the response from the JSON parser is not a dictionary, but an array given the string you pass in. Your code works because -valueForKey:
is something an array will respond to. The array sends -valueforKey:
to each element and builds an array out of the responses.
There are two ways you can do what you want (at least)
Iterate through the array explicitly
NSMutableArray* list = [[NSMutableArray alloc] init]; for (id anObject in response) { [list addObject: [NSString stringWithFormat: @"%@ %@", [anObject objectForKey: @"fName"], [anObject objectForKey: @"lname"]]]; }
Add a category to NSDictionary
@interface NSDictionary(FullName) -(NSString*) fullName; @end @implementation NSDictionary(FullName) -(NSString*) fullName { return [NSString stringWithFormat: @"%@ %@", [self objectForKey: @"fName"], [self objectForKey: @"lname"]]; } @end
Then your existing code changes to
list = (NSArray *)[feed valueForKey:@"fullName"];
精彩评论