你好,所以我试图解析一个json,但每次我尝试失败。我已经尝试过这种方法,我最近使用过,除了这个以外的所有其他项目。 json是有效的。
NSString *post = [NSString stringWithFormat:@"x=2&y=3&z=1"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[[NSURL alloc] initWithString:@"link-to-php.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSError *error;
NSMutableDictionary *getJsonData = [NSJSONSerialization
JSONObjectWithData:requestHandler
options:NSJSONReadingMutableContainers
error:&error];
if( error )
{
NSLog(@"%@", [error localizedDescription]);
}
else {
NSArray *json = getJsonData[@"data"];
for ( NSDictionary *jsn in json )
{
NSLog(@"dea %@",jsn[@"content"]);
}
}
我的JSON代码就是这个
{"status":1,"error_message":null,"data":{"name":"Test","img":"","content":"Continut de test"}}
我得到的错误是
[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x17e7b7c0
2015-08-03 14:58:50.706 InfoCons[4418:1720073] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x17e7b7c0'
答案 0 :(得分:0)
你的json formate返回字典中的字典格式数据而不是数组格式返回"数据"键。
尝试此代码从json获取数据:
if( error )
{
NSLog(@"%@", [error localizedDescription]);
}
else {
NSLog(@"%@",getJsonData[@"data"][@"content"]); // print value of dictionary
}