• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 无法从 NSDictionary 和 JSON 获取值

[复制链接]
菜鸟教程小白 发表于 2022-12-12 17:16:37 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试使用从 json 获得的数据构建一些对象。

不幸的是,尽管尝试了很多次,但我在访问元素时一直遇到问题,但所有尝试都失败了。

代码是:

   [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:restURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (error) {
        NSLog(@"Log error thing: %@", error);
    } else {
        NSLog(@"THE DATA IS REAL: %@", data);

        NSMutableArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        NSLog(@"%@", jsonArray);

        for (NSDictionary *item in jsonArray){
            NSString *val = item[@"title"];
            NSLog(@"AN ITEM: %@ %@", item, val);
        }

    }
}];

打印了“数据是真实的”行,json 目前只包含一项,但会包含更多,并且结构如下:

2015-11-21 11:37:06.313 UnfoldApp[20444:562253] {
timelines =     (
            {
        "__v" = 1;
        "_id" = 564fff17b6db3ccd0529e410;
        creationDate = "2015-11-21T05:18:42.293Z";
        location = Norwich;
        picture = "http://photos4.meetupstatic.com/photos/event/a/9/b/c/600_384643452.jpeg";
        posts =             (
                            {
                "__v" = 0;
                "_id" = 564fff49b6db3ccd0529e411;
                content = "Tonight saw 134 people witness 26 pitches from this years Sync the City attendees. All had a minute each to deliver their business idea. Voting then began. The audience selected their favourite business ideas. Leaving 14 new business leaders ready to form their teams. Over the next hour all participants gravitated towards the business idea that most ...";
                creationDate = "2015-11-21T05:18:42.299Z";
                eventDate = "2015-11-17T22:33:45.000Z";
                heading = "Sync The City Pitches 2015 - Norfolk Tech Journal";
                imageFilename = "http://www.norfolktechjournal.com/wp-content/uploads/2015/11/Sync-the-City-the-Pitches.jpg";
                keywords = "City,Student Rental Service,Guerilla Network Pitch,Chris Spalton Photos,Help Majorie Pitch #,NHS,House,Prototype City Pitch,Tim Stephenson";
                location = doh;
                relatedPosts =                     (
                );
                slug = "sync-the-city-pitches-2015-norfolk-tech-journal";
            }
        );
        slug = "sync-the-city";
        title = "Sync the City";
    }
);

}

[NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:restURL] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    if (error) {
        NSLog(@"Log error thing: %@", error);
    } else {
        NSLog(@"THE DATA IS REAL: %@", data);

        NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@", jsonArray);



        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonArray options:kNilOptions error:nil];
       // NSLog(@"Dictionary: %@", [json objectForKey"title"]);



}

当我尝试访问元素时会出现错误,在这种情况下,它是我迭代 jSonarray 中的项目的地方。

堆栈跟踪:

   2015-11-21 11:37:06.314 UnfoldApp[20444:562253] -[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x79d5c110
2015-11-21 11:37:06.317 UnfoldApp[20444:562253] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x79d5c110'
*** First throw call stack:
(
    0   CoreFoundation                      0x02199a84 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x01c5ae02 objc_exception_throw + 50
    2   CoreFoundation                      0x021a2dd3 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
    3   CoreFoundation                      0x020e0cdd ___forwarding___ + 1037
    4   CoreFoundation                      0x020e08ae _CF_forwarding_prep_0 + 14
    5   UnfoldApp                           0x0009bc39 __33-[AppDelegate someShittyFunction]_block_invoke + 649
    6   CFNetwork                           0x025ccb62 __67+[NSURLConnection sendAsynchronousRequest:queue:completionHandler:]_block_invoke_2 + 177
    7   Foundation                          0x01907a6b __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    8   Foundation                          0x0182b8ff -[NSBlockOperation main] + 108
    9   Foundation                          0x0180bd84 -[__NSOperationInternal _start:] + 697
    10  Foundation                          0x0180bac4 -[NSOperation start] + 83
    11  Foundation                          0x0180b902 __NSOQSchedule_f + 245
    12  libdispatch.dylib                   0x02b9a9cd _dispatch_client_callout + 14
    13  libdispatch.dylib                   0x02b7e650 _dispatch_queue_drain + 2227
    14  libdispatch.dylib                   0x02b7db04 _dispatch_queue_invoke + 570
    15  libdispatch.dylib                   0x02b807bb _dispatch_root_queue_drain + 550
    16  libdispatch.dylib                   0x02b8058e _dispatch_worker_thread3 + 115
    17  libsystem_pthread.dylib             0x02eba270 _pthread_wqthread + 1050
    18  libsystem_pthread.dylib             0x02eb7f82 start_wqthread + 34
)
libc++abi.dylib: terminating with uncaught exception of type NSException

感谢您的帮助,非常感谢。



Best Answer-推荐答案


你能在解析时试试这个吗:

if (error) {
        NSLog(@"Log error thing: %@", error);
} else {
        NSLog(@"THE DATA IS REAL: %@", data);
// this will be your actaul dictionary
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]];

// Array of Timelines
        NSArray* timelineArray = jsonObject[@"timelines"];
        NSLog(@"%@", timelineArray);

// Get Title from Timeline Dictionary
       if (timelineArray.count > 0){
          NSDictionary *timelineDictionary = timelineArray.firstObject;
          NSLog(@"Title: %@", timelineDictionary[@"title"]);
      }
}

关于ios - 无法从 NSDictionary 和 JSON 获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33842901/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap