I am new to objective-C, please help me to sort out this problem, I have a dictionary something like this
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.
__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.
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// do stuff and access the data here
}] resume];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.