如何从JSON获取数据?

时间:2022-12-04 15:38:40

I am getting response back in JSON format and have never parsed it in the past, so could somebody please help me understand this. Here's the Json response i am getting:

我收到JSON格式的回复,过去从未解析过,所以有人可以帮我理解这一点。这是我得到的Json回复:

Twitter response:

(
    {
        contributors = "<null>";
        coordinates = "<null>";
        "created_at" = "Tue Nov 29 15:48:35 +0000 2011";
        entities =         {
            hashtags =             (
            );
            media =             (
                                {
                    "display_url" = "pic.twitter.com/650E1WRY";
                    "expanded_url" = "http://twitter.com/ashu1702/status/141544088850796545/photo/1";
                    id = 141544088854990848;
                    "id_str" = 141544088854990848;
                    indices =                     (
                        22,
                        42
                    );
                    "media_url" = "http://p.twimg.com/AfbdmVBCEAAPJvT.jpg";
                    "media_url_https" = "https://p.twimg.com/AfbdmVBCEAAPJvT.jpg";
                    sizes =                     {
                        large =                         {
                            h = 279;
                            resize = fit;
                            w = 215;
                        };
                        medium =                         {
                            h = 279;
                            resize = fit;
                            w = 215;
                        };
                        small =                         {
                            h = 279;
                            resize = fit;
                            w = 215;
                        };
                        thumb =                         {
                            h = 150;
                            resize = crop;
                            w = 150;
                        };
                    };
                    type = photo;
                    url = "http://t.co/650E1WRY";
                }
            );
            urls =             (
            );
            "user_mentions" =             (
            );
        };
        favorited = 0;
        geo = "<null>";
        id = 141544088850796545;
        "id_str" = 141544088850796545;
        "in_reply_to_screen_name" = "<null>";
        "in_reply_to_status_id" = "<null>";
        "in_reply_to_status_id_str" = "<null>";
        "in_reply_to_user_id" = "<null>";
        "in_reply_to_user_id_str" = "<null>";
        place = "<null>";
        "possibly_sensitive" = 0;
        "retweet_count" = 0;
        retweeted = 0;
        source = "<a href=\"http://www.apple.com\" rel=\"nofollow\">iOS</a>";
        text = "I am in Syria @(null) http://t.co/650E1WRY";
        truncated = 0;
        user =         {
            "contributors_enabled" = 0;
            "created_at" = "Sun May 01 15:20:52 +0000 2011";
            "default_profile" = 1;
            "default_profile_image" = 1;
            description = "<null>";
            "favourites_count" = 0;
            "follow_request_sent" = "<null>";
            "followers_count" = 0;
            following = "<null>";
            "friends_count" = 5;
            "geo_enabled" = 0;
            id = 291164338;
            "id_str" = 291164338;
            "is_translator" = 0;
            lang = en;
            "listed_count" = 0;
            location = "<null>";
            name = "Ashutosh Tiwari";
            notifications = "<null>";
            "profile_background_color" = C0DEED;
            "profile_background_image_url" = "http://a0.twimg.com/images/themes/theme1/bg.png";
            "profile_background_image_url_https" = "https://si0.twimg.com/images/themes/theme1/bg.png";
            "profile_background_tile" = 0;
            "profile_image_url" = "http://a2.twimg.com/sticky/default_profile_images/default_profile_3_normal.png";
            "profile_image_url_https" = "https://si0.twimg.com/sticky/default_profile_images/default_profile_3_normal.png";
            "profile_link_color" = 0084B4;
            "profile_sidebar_border_color" = C0DEED;
            "profile_sidebar_fill_color" = DDEEF6;
            "profile_text_color" = 333333;
            "profile_use_background_image" = 1;
            protected = 0;
            "screen_name" = ashu1702;
            "show_all_inline_media" = 0;
            "statuses_count" = 62;
            "time_zone" = "<null>";
            url = "<null>";
            "utc_offset" = "<null>";
            verified = 0;
        };
    }
)

Specifically i just need the "expanded_url" and i am doing this in my code to get it:

具体来说,我只需要“expanded_url”,我在我的代码中执行此操作来获取它:

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];// where response data is coming from the call made to twitter timeline_api

                          NSString * callBackURL = [dict objectForKey:@"expanded_url"];

On doing this i am getting this error:

这样做我得到这个错误:

2011-11-29 09:50:31.214 L'Occitane[1119:19d07] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x85a50d0
2011-11-29 09:50:31.215 L'Occitane[1119:19d07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x85a50d0'

PLease help!!!

Thanks,

1 个解决方案

#1


7  

When converted to Cocoa Foundation objects, JSON decomposes into a bunch of nested NSArrays and NSDictionarys ultimately leading to NSStrings, NSNumbers and NSNulls. Ideally you'd work forwards from the web service's documentation but you can work backwards from the description that the root object prints through NSLog.

当转换为Cocoa Foundation对象时,JSON会分解为一堆嵌套的NSArrays和NSDictionarys,最终导致NSStrings,NSNumbers和NSNulls。理想情况下,您可以从Web服务的文档向前工作,但您可以从根对象通过NSLog打印的描述向后工作。

From your log I can see that expanded_url is a member of an unnamed object which is the first entry in the media array that is a member of the entities object. The unnamed object containing entities is part of an array, which is what the JSON deserialiser will return. So you want to do something like (if written out in long form for exposition, and without any validation):

从您的日志中我可以看到expanded_url是未命名对象的成员,该对象是媒体数组中作为entities对象成员的第一个条目。包含实体的未命名对象是数组的一部分,这是JSON反序列化器将返回的内容。所以你想要做类似的事情(如果以长篇形式写出来进行展示,并且没有任何验证):

NSArray *result = [NSJSONSerialization ...

NSDictionary *firstObject = [result objectAtIndex:0];
NSDictionary *entities = [firstObject objectForKey:@"entities"];
NSArray *media = [entities objectForKey:@"media"];
NSDictionary *relevantObject = [media objectAtIndex:0];
NSString *expandedUrl = [relevantObject objectForKey:@"expanded_url"];

The main risk in there is that the web service may return an empty array for media, causing objectAtIndex:0 to raise an exception, or that it will return something other than an array as the root object or in some other way adjust a type somewhere along the line. Objective-C's usual rules about messaging nil should save you from most problems with the dictionaries. Quite how much validation to apply is a judgment call.

其中的主要风险是Web服务可能会为媒体返回一个空数组,导致objectAtIndex:0引发异常,或者它将返回除数组以外的其他内容作为根对象或以某种其他方式调整某个类型的某个类型沿线。 Objective-C关于消息传递的通常规则应该可以避免大多数字典问题。相当多的验证适用于判断调用。

#1


7  

When converted to Cocoa Foundation objects, JSON decomposes into a bunch of nested NSArrays and NSDictionarys ultimately leading to NSStrings, NSNumbers and NSNulls. Ideally you'd work forwards from the web service's documentation but you can work backwards from the description that the root object prints through NSLog.

当转换为Cocoa Foundation对象时,JSON会分解为一堆嵌套的NSArrays和NSDictionarys,最终导致NSStrings,NSNumbers和NSNulls。理想情况下,您可以从Web服务的文档向前工作,但您可以从根对象通过NSLog打印的描述向后工作。

From your log I can see that expanded_url is a member of an unnamed object which is the first entry in the media array that is a member of the entities object. The unnamed object containing entities is part of an array, which is what the JSON deserialiser will return. So you want to do something like (if written out in long form for exposition, and without any validation):

从您的日志中我可以看到expanded_url是未命名对象的成员,该对象是媒体数组中作为entities对象成员的第一个条目。包含实体的未命名对象是数组的一部分,这是JSON反序列化器将返回的内容。所以你想要做类似的事情(如果以长篇形式写出来进行展示,并且没有任何验证):

NSArray *result = [NSJSONSerialization ...

NSDictionary *firstObject = [result objectAtIndex:0];
NSDictionary *entities = [firstObject objectForKey:@"entities"];
NSArray *media = [entities objectForKey:@"media"];
NSDictionary *relevantObject = [media objectAtIndex:0];
NSString *expandedUrl = [relevantObject objectForKey:@"expanded_url"];

The main risk in there is that the web service may return an empty array for media, causing objectAtIndex:0 to raise an exception, or that it will return something other than an array as the root object or in some other way adjust a type somewhere along the line. Objective-C's usual rules about messaging nil should save you from most problems with the dictionaries. Quite how much validation to apply is a judgment call.

其中的主要风险是Web服务可能会为媒体返回一个空数组,导致objectAtIndex:0引发异常,或者它将返回除数组以外的其他内容作为根对象或以某种其他方式调整某个类型的某个类型沿线。 Objective-C关于消息传递的通常规则应该可以避免大多数字典问题。相当多的验证适用于判断调用。