In iOS, how do I parse a JSON string into an object

前端 未结 7 834
日久生厌
日久生厌 2021-02-08 05:41

I come from Android dev, so sorry if I\'m missing obvious iOS concepts here.

I have a JSON feed that looks like:

{\"directory\":[{\"id\":0,\"fName\":\"...\

7条回答
  •  鱼传尺愫
    2021-02-08 06:37

    You can do it like

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];//response object is your response from server as NSData
    
    if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
        NSArray *yourStaffDictionaryArray = json[@"directory"];
        if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){//Added instrospection as suggested in comment.
            for (NSDictionary *dictionary in yourStaffDictionaryArray) {
                Staff *staff = [[Staff alloc] init];
                staff.id = [[dictionary objectForKey:@"id"] integerValue];
                staff.fname = [dictionary objectForKey:@"fName"];
                staff.lname = [dictionary objectForKey:@"lName"]; 
                //Do this for all property
                [yourArray addObject:staff];
            }
        }
    }
    

提交回复
热议问题