How to parse JSON into Objective C - SBJSON
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] ini开发者_如何转开发t];
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
Note that your JSON data has the following structure:
- the top level value is an object (a dictionary) that has a single attribute called ‘lessons’
- the ‘lessons’ attribute is an array
- each element in the ‘lessons’ array is an object (a dictionary containing a lesson) with several attributes, including ‘stunde’
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:
, theerror
parameter is a pointer to a pointer. It’s more common to useNULL
instead ofnil
in that case. It’s also a good idea not to passNULL
and use anNSError
object to inspect the error in case the method returnsnil
If
jsonObject
is used only in that particular method, you probably don’t need to copy it. The code above doesn’t.
精彩评论