如何将Dictionary值放入数组?

时间:2017-01-25 04:30:19

标签: ios objective-c arrays json dictionary

我是Objective-C的新手,请帮我解决这个问题,我有一个类似的字典

Async JSON: (
        {
        "cus_name" = cus1;
        "cus_id" = 001;
    },
        {
        "cus_name" = cus2;
        "job_id" = 002;
    }
)

但我需要与此相同的输出:

Async JSON:(
        (
        cus1,
        001
    ),
        (
        cus2,
        002
    )
)

请帮我解决这个问题,这是我用过的代码:

 NSData *cityData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:strURL]];

__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                           json = [NSJSONSerialization JSONObjectWithData:data
                                                                  options:0
                                                                    error:nil];
                           NSLog(@"Async JSON: %@", json);
                       }];

1 个答案:

答案 0 :(得分:2)

你在这里犯了错误,你的JSON响应不是Dictionary它是字典数组,如果要转换嵌套数组,请尝试这样。

__block NSMutableArray *nestedArray = [NSMutableArray array];
[NSURLConnection sendAsynchronousRequest:request
                               queue:[NSOperationQueue mainQueue]
                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                       NSArray *json = [NSJSONSerialization JSONObjectWithData:data
                                                              options:0
                                                                error:nil];

                    for (NSDictionary* dic in json) {
                        NSMutableArray *subArray = [NSMutableArray array];
                        [subArray addObject:[dic objectForKey:@"cus_name"]];
                        if ([dic objectForKey:@"cus_id"]) {
                            [subArray addObject:[dic objectForKey:@"cus_id"]];
                        }
                        if ([dic objectForKey:@"job_id"]) {
                            [subArray addObject:[dic objectForKey:@"job_id"]];
                        }
                        [nestedArray addObject:subArray];
                    }

                   }];

注意:NSURLConnection开始,我已弃用,建议您像这样使用NSURLSession

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:request 
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

     // do stuff and access the data here

}] resume];