簡體   English   中英

如何將字典值放入數組中?

[英]How to put the Dictionary values to an array?

我是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);
                       }];

您在這里犯了錯誤,您的JSON響應不是Dictionary ,而是Dictionary的Array,如果您想將其轉換為嵌套數組,請嘗試這樣。

__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

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

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

     // do stuff and access the data here

}] resume];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM