2011-02-07 92 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