How to parse JSON into Objective C - SBJSON

前端 未结 1 1166

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\         


        
1条回答
  •  有刺的猬
    2020-12-03 13:05

    Note that your JSON data has the following structure:

    1. the top level value is an object (a dictionary) that has a single attribute called ‘lessons’
    2. the ‘lessons’ attribute is an array
    3. 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:, 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.

    0 讨论(0)
提交回复
热议问题