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

前端 未结 7 832
日久生厌
日久生厌 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:22

    you can use NSJSonSerialisation or AFNetworking library. Here is the example of AFNetworking to parse json response

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        NSDictionary *json = (NSDictionary *)responseObject;
        NSArray *staffArray = json[@"directory"];
    
    [staffArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop){
          Staff *staff = [[Staff alloc] init];
        staff.id = [[obj objectForKey:@"id"] integerValue];
        staff.fname = [obj objectForKey:@"fName"];
        staff.lname = [obj objectForKey:@"lName"]; 
    
       //add data to new array to store details
       [detailsArray addObect:staff);
    } ];
    
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }]; 
    

    then use Core Data framework to store data.

提交回复
热议问题