1

这是我的代码:

    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:。
我在哪里做错了?

4

2 回答 2

2

问题是,虽然键“LoginPOST2Result”的 json 响应中的值看起来像一个字典,但它实际上是一个字符串,因为它用引号引起来。

因此,您将 objectForKey: 消息发送到 NSString 而不是 NSDictionary。NSString 不响应 objectForKey:。

看起来 webServiceResponse 生成不正确或解析不正确。

于 2011-10-22T12:49:57.817 回答
1

您需要更好地理解 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-22T12:53:08.797 回答