【问题标题】:Unable to get JSON from String无法从字符串获取 JSON
【发布时间】:2016-12-07 18:40:44
【问题描述】:

我将 newDetails 的值作为字符串获取。当我尝试以下代码时,我得到一个异常

[__NSArrayI dataUsingEncoding:]: 无法识别的选择器发送到实例。

我已将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];

谁能告诉我为什么会出现异常?

【问题讨论】:

  • 我的猜测是键“newDetail”的值不是字符串,而是其他一些数据类型。可能是 [NSNull null]。
  • 我正在打印newDetail的值,它不为空
  • 你确定它是以字符串而不是字典的形式返回的吗?打印出来的行不明确。
  • 是的,我确定。
  • 这可能是valueForKey: 陷阱。使用 response[@"newDetail"] 会发生什么?

标签: ios objective-c json


【解决方案1】:

在我看来,以下代码返回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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-31
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2016-06-30
    • 2015-02-07
    • 2016-08-28
    相关资源
    最近更新 更多