[英]How to put the Dictionary values to an array?
I am new to objective-C, please help me to sort out this problem, I have a dictionary something like this 我是Objective-C的新手,请帮助我解决此问题,我有这样的字典
Async JSON: (
{
"cus_name" = cus1;
"cus_id" = 001;
},
{
"cus_name" = cus2;
"job_id" = 002;
}
)
But I need that output same as this: 但我需要与此相同的输出:
Async JSON:(
(
cus1,
001
),
(
cus2,
002
)
)
Please help me how to sort out this, this is the code I have used: 请帮助我解决这个问题,这是我使用的代码:
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);
}];
You are making mistake here, your JSON response is not Dictionary
it is Array of dictionary, if you want to convert it nested array, try like this. 您在这里犯了错误,您的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];
}
}];
Note: As of NSURLConnection
is deprecated I'm, suggesting you to use NSURLSession
like this way. 注意:自不推荐使用
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.