2011-11-29 22 views
4

JSON 형식으로 응답을 보내고 있으며 과거에 구문 분석을 해 본 적이 없으므로 이해해 주시기 바랍니다.JSON에서 데이터를 가져 오는 방법은 무엇입니까?

트위터 응답 :

(
    { 
     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; 
     }; 
    } 
) 

구체적 난 그냥 "expanded_url"을 필요로하고 내가 그것을 얻기 위해 내 코드에서이 일을하고있다 : 여기에 내가 무엇입니까 JSON 응답의

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"]; 

이렇게하면이 오류가 발생합니다 :

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' 

더 도움이됩니다. 코코아 재단 객체로 변환 할 때

덕분에,

답변

7

, JSON은 궁극적으로 NSString의, NSNumber s와 NSNull들로 이어지는 중첩 NSArraysNSDictionary s의 무리로 분해. 이상적으로 웹 서비스 문서에서 앞으로 진행할 것이지만 루트 객체가 인쇄 한 설명에서 뒤로 작업 할 수 있습니다 (NSLog).

로그에서 expanded_urlentities 개체의 구성원 인 media 배열의 첫 번째 항목 인 익명의 개체의 구성원임을 알 수 있습니다. 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"]; 

웹 서비스가 objectAtIndex:0 원인 media에 대한 빈 배열을 반환 할 수 있습니다에 주요 위험 예외를 발생 시키거나 배열 이외의 다른 것을 루트 객체로 반환하거나 다른 방법으로 행을 따라 어딘가에 유형을 조정할 것입니다. Objective-C의 메시징에 대한 일반적인 규칙 인 nil을 사용하면 사전의 대부분의 문제를 방지 할 수 있습니다. 얼마나 많은 유효성 확인을 적용 할 것인가는 판단을 요구하는 것입니다.

+0

대단히 감사합니다! – Ashutosh

관련 문제