2011-02-07 97 views
8

你能告诉我如何传递一个JSON字符串,它看起来像这样:如何解析JSON到目标C - SBJSON

{"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数据结构如下

问候

+0

谢谢:)不知道在哪里:) – Chris 2011-02-07 10:15:02

回答

22

注:

  1. 顶层值是一个对象(字典),其具有所谓的“吸取”
  2. 的“课程”属性是一个数组
  3. 每个元素在“课程”阵列是单个属性

    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"]; 
    
    } 
    
    :对象具有多个属性,包括 'stunde'

相应的代码是(含有课词典)

几个观察:

  • -objectWithString:error:,所述error参数是一个指向指针的指针。在这种情况下,使用NULL而不是nil更为常见。这也是一个不错的主意通过NULL,并使用NSError对象进行检查的情况下,如果jsonObject仅用于在特定的方法,该方法返回nil

  • 的错误,你可能并不需要复制。上面的代码没有。

+0

谢谢老兄:) – Chris 2011-02-07 09:54:38