Reputation: 200
Could you please tell me how to pass a JSON String which looks like this:
{"lessons":[{"id":"38","fach":"D","stunde":"t1s1","user_id":"1965","timestamp":"0000-00-00 00:00:00"},{"id":"39","fach":"M","stunde":"t1s2","user_id":"1965","timestamp":"0000-00-00 00:00:00"}]}
I tried it like this:
SBJSON *parser =[[SBJSON alloc] init];
NSArray *list = [[parser objectWithString:JsonData error:nil] copy];
[parser release];
for (NSDictionary *stunden in list)
{
NSString *content = [[stunden objectForKey:@"lessons"] objectForKey:@"stunde"];
}
thanks in advance
best regards
Upvotes: 8
Views: 19784
Reputation:
Note that your JSON data has the following structure:
The corresponding code is:
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
// 1. get the top level value as a dictionary
NSDictionary *jsonObject = [parser objectWithString:JsonData error:NULL];
// 2. get the lessons object as an array
NSArray *list = [jsonObject objectForKey:@"lessons"];
// 3. iterate the array; each element is a dictionary...
for (NSDictionary *lesson in list)
{
// 3 ...that contains a string for the key "stunde"
NSString *content = [lesson objectForKey:@"stunde"];
}
A couple of observations:
In -objectWithString:error:
, the error
parameter is a pointer to a pointer. It’s more common to use NULL
instead of nil
in that case. It’s also a good idea not to pass NULL
and use an NSError
object to inspect the error in case the method returns nil
If jsonObject
is used only in that particular method, you probably don’t need to copy it. The code above doesn’t.
Upvotes: 22