ios - 无法从字符串获取 JSON

标签 ios objective-c json

我以字符串形式获取 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/

相关文章:

objective-c - 加密核心数据

ios - 如何在 iOS 自定义键盘中添加自定义通知?

ios - 是否有任何简单的方法可以在所有方法中添加NSLog或任何日志记录语句?

java - 通过 JSON 和 PHP 发送电子邮件后出现 NullpointerException

javascript - 带有键值的 ng-if 条件 - Angular js

ios - iOS 11 UISearchController 上的 UIToolbar 按钮未调用操作

objective-c - iphone : CGRectInterest, HitTest

objective-c - 在 Cocoa 中查找文件的最后访问日期

json - 在 RESTful Web 服务中,响应 DTO 是否应该包含它们的子 DTO?

ios - Rider Xamarin iOS 错误 "application bundle was not generated after deployment"