您能否告诉我如何传递如下所示的JSON字符串:
{"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"}]}
我这样尝试过:
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"]; }
提前致谢
最好的祝福
请注意,您的JSON数据具有以下结构:
相应的代码是:
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"]; }
一些观察:
在中-objectWithString:error:,error参数是指向指针的指针。在这种情况下,通常使用NULL代替nil。如果方法返回,则 不要 传递NULL并使用NSError对象检查错误也是一个好主意nil
-objectWithString:error:
error
NULL
nil
NSError
如果jsonObject仅用于该特定方法,则可能不需要复制它。上面的代码没有。
jsonObject