这是我的代码:
NSError *error = nil;
SBJsonParser *parserJson = [[SBJsonParser alloc] init];
NSDictionary *jsonObject = [parserJson objectWithString:webServiceResponse error:&error];
[parserJson release], parserJson = nil;
//Test to see if response is different from nil, if is so the parsing is ok
if(jsonObject != nil){
//Get user object
NSDictionary *userJson = [jsonObject objectForKey:@"LoginPOST2Result"];
if(userJson != nil){
self.utente = [[User alloc] init];
self.utente.userId = [userJson objectForKey:@"ID"];
}
而Json字符串webServiceResponse是:
{"LoginPOST2Result":
"{\"ID\":1,
\"Username\":\"Pippo\",
\"Password\":\"Pippo\",
\"Cognome\":\"Cognome1\",
\"Nome\":\"Nome1\",
\"Telefono\":\"012345678\",
\"Email\":null,
\"BackOffice\":true,
\"BordoMacchina\":false,
\"Annullato\":false,
\"Badge\":1234}"
}
当执行下面这行代码时,问题就出现了:
self.utente.userId = (NSInteger *) [userJson objectForKey:@"ID"];
错误是:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString objectForKey:]: unrecognized selector sent to instance 0x6861520'
这个错误似乎是因为对象userJson不是NSDictionary类型,而是NSCFString类型,因此不会响应消息objectForKey:。
我哪里做错了?
发布于 2011-10-22 12:53:09
您需要更好地理解什么是指针,以及在Cocoa框架中什么是不是。
实际上,您将userJson定义为NSDictionary,而不是NSDictionary *。考虑到Cocoa中的所有对象都是指针。事实上,检查NSDictionary objectForKey:返回"id“,然后必须使用NSDictionary *。简单地使用NSDictionary就可以引用这个类。
类似的错误在后面的强制转换(NSInteger *)但是NSInteger (NSInteger不是一个对象,它是一个从long或int (取决于平台架构)中犹豫的基本类型),正如你可以从它的定义中看到的:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
而且,从上面的对象定义看,您尝试获取的键被转储为字符串,并且您正在尝试获取字典。请检查原始的json,它可能不是您期望的格式。
所以在最后,你至少有3个错误会让你的应用崩溃。
发布于 2011-10-22 12:49:58
问题是,尽管键"LoginPOST2Result“的json响应中的值看起来像一个字典,但它实际上是一个字符串,因为它包含在引号中。
因此,您要将objectForKey:消息发送到NSString而不是NSDictionary。NSString不响应objectForKey:。
看起来像是错误地生成或解析了webServiceResponse。
https://stackoverflow.com/questions/7859584
复制相似问题