ios - 我如何从 JSON 数据中获取 NSString 对象

标签 ios json parsing

<分区>

我是 iOS 初学者,我在编码方面遇到了一些麻烦。 通过发送 ASIHTTPRequest:

NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/search.json?geocode=37.781157,-122.398720,25km"];

我收到这样的数据:

            {
        "created_at" = "Fri, 25 Jan 2013 17:48:29 +0000";
        "from_user" = "ZacHWallS_SBI";
        "from_user_id" = 252712138;
        "from_user_id_str" = 252712138;
        "from_user_name" = "ZACH WALLS";
        geo = "<null>";
        id = 294864332490162176;
        "id_str" = 294864332490162176;
        "in_reply_to_status_id" = 294861687004225537;
        "in_reply_to_status_id_str" = 294861687004225537;
        "iso_language_code" = en;
        location = "BAY AREA CALIFORNIA";
        metadata =             {
            "result_type" = recent;
        };
        "profile_image_url" = "http://a0.twimg.com/profile_images/3029389178/e3567459d147bc5d0a10f3c797b477aa_normal.png";
        "profile_image_url_https" = "https://si0.twimg.com/profile_images/3029389178/e3567459d147bc5d0a10f3c797b477aa_normal.png";
        source = "&lt;a href=&quot;http://twitter.com/#!/download/ipad&quot;&gt;Twitter for iPad&lt;/a&gt;";
        text = "@LilTioSBi yee ima slide through prolly";
        "to_user" = LilTioSBi;
        "to_user_id" = 35629694;
        "to_user_id_str" = 35629694;
        "to_user_name" = "Nevin Tio";
    },

接下来我这样做:

-(void) requestFinished: (ASIHTTPRequest *) request {
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON];
//NSLog(@"\n\n%@", jsonDictionary);  
NSMutableArray *userName = [userinfo objectForKey:@"from_user"];
NSLog(@"\n\n\n%@",userName);

我需要捕获“from_user”。 然后运行,编译器说:[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x755bbc0... 如何正确操作?

最佳答案

所以,我首先要澄清一些事情,即它实际上是运行时给你的“[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x755bbc0”错误。

让我们分解一下:

__NSArrayM 听起来很像 NSArray(NSArray 在技术上是一种叫做类簇的东西,这意味着你不会总是看到准确的 NSArray 在实践中,只是像一个一样工作的东西)。

-objectForKey:NSDictionary

上的一个方法

因此,我们在我们认为是字典的数组上调用方法(调用方法 = 发送消息,或者用 ObjC 的说法是“选择器”)。

似乎您省略了一些代码,但如果您只是从以下内容传递了值:

[jsonDictionary objectForKey:@"results"]

您最终会得到一系列推文。然后,您需要从该数组中获取一个项目以获取其 from_user 键。

NSArray *tweets = [jsonDictionary objectForKey:@"results"];
NSDictionary *tweet = [tweets objectAtIndex:0];
NSString *username = [tweet objectForKey:@"from_user"];

关于ios - 我如何从 JSON 数据中获取 NSString 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528025/

相关文章:

ios - 如何使用原生 webrtc 中的约束?

php - 为 JSON 字符串编码 HTML

json - WildFly 在全局范围内支持开发中的 pretty-print ,但不支持生产中

json - 使用 F# 解析 JSON(不是序列化)

c++ - 检索 C++ 程序/文件中使用的指针变量列表

ios - 如何将 preferredMaxLayoutWidth 用作我的 UILabel 的自动设置并找出其 View 的高度?

ios - 将 subview 添加到外部屏幕(iOS5)

ios - 为什么从 iOS7 迁移后 iOS8 SSL 请求间歇性失败?

Android+JSON解析使用SOAP webservices

javascript - 从没有 ID 的 HTML 中解析数据