我正在使用AFNetworking来获取JSON对象:
-(void)getData{
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
@"MyAudioMemo.m4a",
nil];
NSURL *filePath = [NSURL fileURLWithPathComponents:pathComponents];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/service.php"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:@"audio" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
service.php页面返回有效的JSON对象:
{"song_id": 2, "song_name": "Red Fang - Wires", "confidence": 120, "offset_seconds": 50.3873, "match_time": 1.0025339126586914, "offset": 1085}
带有JSON标头:
header('Content-type: application/json');
但是,这是responseObject的输出:
Success: {
confidence = 120;
"match_time" = "1.035004138946533";
offset = 1085;
"offset_seconds" = "50.3873";
"song_id" = 2;
"song_name" = "Red Fang - Wires";
}
顺序被更改,并且某些引号被去除。每当我尝试使用responseObject的值(“ song_name”的执行点)时,我的应用都会崩溃,
-[__NSCFNumber length]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance
我究竟做错了什么 ?
最佳答案
在您的JSON对象中,除了song_name之外的所有内容都是一个NSNumber(它不理解选择器的“长度”)。您可以使用选择器“ stringValue”将NSNumber转换为NSString。
像这样:
NSString* song_id_str = [responseObject[@"song_id"] stringValue];
或者您只使用NSNumber
NSNumber* song_id = responseObject[@"song_id"];