本文介绍了iOS解析数据时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我使用JSON解析数据

In my app, I am parsing the data using JSON

NSString * urlString=[NSString stringWithFormat:@"http://[email protected]&latitude=59.34324&longitude=23.359257"];
NSURL * url=[NSURL URLWithString:urlString];
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError * error;
NSURLResponse * response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * outputData=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@",outputData);

SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:outputData error:nil];
NSLog(@"%@",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:@"success"] integerValue];

执行此代码后,在我的日志中将其打印为

After this code executes, In my log it is printed as

({
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},
{
latitude = "80.000000000000000";
longitude = "30.000000000000000";
username = arun;
})

但是在运行时,该应用程序崩溃了,如

But while running, the app crashes, as

'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x910d8d0'

推荐答案

我认为您的问题是,jsonParser objectWithString返回一个包含字典的数组,而不是字典本身.

I think your problem is, that jsonParser objectWithString returns an array with dictionaries in it not dictionaries itself.

请尝试以下操作:

NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];

for(NSDictionary *dict in jsonData) {
    NSLog(@"%@",dict);
}

这对您有用吗?

这篇关于iOS解析数据时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 20:15