我以字符串形式获取 newDetails 的值。当我尝试以下代码时,出现异常
[__NSArrayI dataUsingEncoding:]: unrecognized selector sent to instance.
我已将 newDetail
声明为 NSString
。此外,此代码和下面的代码中的 newDetail
的值是相同的。
这是代码:
newDetail = [response valueForKey:@"newDetail"];
//newDetail prints as {"number":1,"nid":"1","pId":"3","name":"","me":"","day":"1"}
NSError *error;
NSData* data = [newDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
但是当我尝试下面的代码时,它运行完美:
newDetail = @" {\"number\":1,\"nid\":\"1\",\"pId\":\"3\",\"name\":\"\",\"me\":\"\",\"day\":\"1\"}";
NSError *error;
NSData* data = [newDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
谁能告诉我为什么我会得到异常(exception)?
最佳答案
在我看来,以下代码返回一个 NSArray
:
newDetail = [response valueForKey:@"newDetail"];
我怀疑这是因为错误消息,该消息指出您尝试在 NSArray
对象上调用方法 -dataUsingEncoding:
。
但是......你提到它打印如下:
{"number":1,"nid":"1","pId":"3","name":"","me":"","day":"1"}
这意味着它是一个 NSDictionary(键/值对)。
您可以记录该类以确保如下所示:
NSLog(@"%@", [newDetail class]);
您的版本之所以有效,是因为您对字符串进行了硬编码。如果您尝试将 NSDictionary 甚至 NSArray 序列化为 JSON 字符串,您应该会得到相同的错误,如下所示:
// This should result in the same error, since we serialize
// an empty dictionary into a JSON string.
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:@{}
options:kNilOptions
error:&error];
关于ios - 无法从字符串获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024932/