-3

我有一个看起来像这样的对象:

{
 "userID": "2A8761E4-C13A-470E-A759-91432D61B6AF-25982-0000352D853511AF"
}

它是来自 AFNetworking JSON 请求的返回值。该对象称为 JSON。

我尝试以几种不同的方式访问 userID 值,但不断收到错误“无法识别的选择器”。这是我尝试过的:

[JSON objectForKey:@"userID"]
[JSON valueForKey:@"userID"]   
[[JSON objectAtIndex:0] valueForKey:@"userID"];
[[JSON objectAtIndex:0] objectForKey:@"userID"];
[JSON objectAtIndex[0]];

什么是正确的语法?

编辑

这是有关无法识别的选择器错误的更多详细信息。

-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x20068150
2013-02-23 15:58:13.993 BMTabbed[12312:907] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x20068150'
*** First throw call stack:
(0x325032a3 0x3a22097f 0x32506e07 0x32505531 0x3245cf68 0xbe9ed 0xbe91b 0xaae8f 0xabe65 0x3a63811f 0x3a6374b7 0x3a63c1bd 0x324d6f3b 0x32449ebd 0x32449d49 0x360202eb 0x3435f301 0x96e95 0x3a657b20)
libc++abi.dylib: terminate called throwing an exception
4

2 回答 2

1

您正在将NSDictionary选择器发送到NSString. 您可以使用NSJSONSerialization将 JSON 字符串转换为NSDictionaryor NSArray,具体取决于 JSON 字符串的根对象。在您的情况下,它是NSDictionary

NSData *data = [NSData dataWithBytes:[json UTF8String] length:[json lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
于 2013-02-23T21:18:35.640 回答
1

如果

NSLog(@"%@", [JSON class]); //=> __NSCFDictionary

然后要么

[JSON objectForKey:@"userID"]

或者

JSON[@"userID"]

应该管用。

于 2013-02-23T21:29:32.543 回答