2011-04-05 60 views
105

我是iPhone新手。任何人都可以告訴我要遵循的步驟來解析這些數據並獲取活動的詳細信息,名字和姓氏嗎?如何使用Objective-C解析JSON?

{ 
    "#error": false, 
    "#data": { 
     "": { 
      "activity_id": "35336", 
      "user_id": "1", 
      "user_first_name": "Chandra Bhusan", 
      "user_last_name": "Pandey", 
      "time": "1300870420", 
      "activity_details": "Good\n", 
      "activity_type": "status_update", 
      "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-1627435117.jpg" 
     }, 
     "boolean": "1", 
     "1": { 
      "1": { 
       "photo_1_id": "9755" 
      }, 
      "activity_id": "35294", 
      "album_name": "Kalai_new_Gallery", 
      "user_id": "31", 
      "album_id": "9754", 
      "user_first_name": "Kalaiyarasan", 
      "user_last_name": "Balu", 
      "0": { 
       "photo_0_id": "9756" 
      }, 
      "time": "1300365758", 
      "activity_type": "photo_upload", 
      "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/" 
     }, 
     "3": { 
      "activity_id": "35289", 
      "user_id": "33", 
      "user_first_name": "Girija", 
      "user_last_name": "S", 
      "time": "1300279636", 
      "activity_details": "girija Again\n", 
      "activity_type": "status_update", 
      "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg" 
     }, 
     "2": { 
      "owner_first_name": "Girija", 
      "activity_id": "35290", 
      "activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}", 
      "activity_type": "friend accept", 
      "owner_last_name": "S", 
      "time": "1300280400", 
      "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg", 
      "owner_id": "33" 
     }, 
     "4": { 
      "activity_id": "35288", 
      "user_id": "33", 
      "user_first_name": "Girija", 
      "user_last_name": "S", 
      "time": "1300279530", 
      "activity_details": "girija from mobile\n", 
      "activity_type": "status_update", 
      "photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg" 
     } 
    } 
} 
+1

請確保您將答案標記爲接受,如果它幫助您的原因。 – 2013-09-19 07:42:47

回答

24

不要重新發明輪子。使用json-framework或類似的東西。

如果你決定使用JSON的框架,這裏是你如何分析JSON字符串轉換成NSDictionary

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease]; 
// assuming jsonString is your JSON string... 
NSDictionary* myDict = [parser objectWithString:jsonString]; 

// now you can grab data out of the dictionary using objectForKey or another dictionary method 
+3

至於「類似的東西」,http://json.org列出了Objective-C的五個JSON解析器。 – 2011-04-05 04:53:12

+3

請注意,其許可證不是標準的開源許可證。在使用庫之前,您可能必須查看它。 – 2013-06-24 09:25:03

+1

使用這個確實比'NSJSONSerialization'提供了什麼優勢嗎? – Kiran 2014-06-10 13:53:34

6
  1. 我推薦及使用TouchJSON解析JSON。
  2. 回答你對亞歷克斯的評論。下面是快速的代碼,應該讓你得到這樣的返回activity_details,姓氏等,從JSON字典中的字段:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"]; 
    NSDictionary *user; 
    NSInteger i = 0; 
    NSString *skey; 
    if(userinfo != nil){ 
        for(i = 0; i < [userinfo count]; i++) { 
         if(i) 
          skey = [NSString stringWithFormat:@"%d",i]; 
         else 
          skey = @""; 
    
         user = [userinfo objectForKey:skey]; 
         NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]); 
         NSLog(@"last_name:%@",[user objectForKey:@"last_name"]); 
         NSLog(@"first_name:%@",[user objectForKey:@"first_name"]); 
         NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]); 
        } 
    } 
    
160

隨着OS X v10.7的角度和iOS 5發佈,可能現在推薦的第一件事是NSJSONSerialization,Apple提供的JSON解析器。如果您發現該類在運行時不可用,請僅將第三方選項用作後備。

因此,舉例來說:

NSData *returnedData = ...JSON data, probably from a web request... 

// probably check here that returnedData isn't nil; attempting 
// NSJSONSerialization with nil data raises an exception, and who 
// knows how your third-party library intends to react? 

if(NSClassFromString(@"NSJSONSerialization")) 
{ 
    NSError *error = nil; 
    id object = [NSJSONSerialization 
         JSONObjectWithData:returnedData 
         options:0 
         error:&error]; 

    if(error) { /* JSON was malformed, act appropriately here */ } 

    // the originating poster wants to deal with dictionaries; 
    // assuming you do too then something like this is the first 
    // validation step: 
    if([object isKindOfClass:[NSDictionary class]]) 
    { 
     NSDictionary *results = object; 
     /* proceed with results as you like; the assignment to 
     an explicit NSDictionary * is artificial step to get 
     compile-time checking from here on down (and better autocompletion 
     when editing). You could have just made object an NSDictionary * 
     in the first place but stylistically you might prefer to keep 
     the question of type open until it's confirmed */ 
    } 
    else 
    { 
     /* there's no guarantee that the outermost object in a JSON 
     packet will be a dictionary; if we get here then it wasn't, 
     so 'object' shouldn't be treated as an NSDictionary; probably 
     you need to report a suitable error condition */ 
    } 
} 
else 
{ 
    // the user is using iOS 4; we'll need to use a third-party solution. 
    // If you don't intend to support iOS 4 then get rid of this entire 
    // conditional and just jump straight to 
    // NSError *error = nil; 
    // [NSJSONSerialization JSONObjectWithData:... 
} 
+0

您可以發佈這種方式的任何示例?我發現缺乏Apple文檔。 – 2013-03-06 18:14:09

+0

@RobertKarl我已經更新了我的答案;希望澄清事情? – Tommy 2013-03-08 00:50:36

+0

是的!謝謝,這很有幫助。特別是,如果沒有一個工作示例(我沒有在他們的文檔中找到一個),傳遞選項和錯誤參數的東西有點神祕。爲什麼開發者傳遞一個對錯誤指針的引用對我來說依然神祕。 – 2013-03-08 22:12:19

16
NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"json"]; 

//將文件內容讀取到字符串中,注意編碼NSUTF8StringEncoding 防止亂碼, 
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 

//將字符串寫到緩衝區。 
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 

NSError *jsonError; 
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError]; 


for (int i=0; i<[allKeys count]; i++) { 
    NSDictionary *arrayResult = [allKeys objectAtIndex:i]; 
    NSLog(@"name=%@",[arrayResult objectForKey:@"storyboardName"]); 

} 

文件:

[ 
    { 
    "ID":1, 
    "idSort" : 0, 
    "deleted":0, 
    "storyboardName" : "MLMember", 
    "dispalyTitle" : "76.360779", 
    "rightLevel" : "10.010490", 
    "showTabBar" : 1, 
    "openWeb" : 0, 
    "webUrl":"" 
    }, 
    { 
    "ID":1, 
    "idSort" : 0, 
    "deleted":0, 
    "storyboardName" : "0.00", 
    "dispalyTitle" : "76.360779", 
    "rightLevel" : "10.010490", 
    "showTabBar" : 1, 
    "openWeb" : 0, 
    "webUrl":"" 
    } 
    ] 
9

JSON解析使用NSJSONSerialization

NSString* path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"]; 

    //Here you can take JSON string from your URL ,I am using json file 
    NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 
    NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; 
    NSError *jsonError; 
    NSArray *jsonDataArray = [[NSArray alloc]init]; 
    jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError]; 

    NSLog(@"jsonDataArray: %@",jsonDataArray); 

    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError]; 
if(jsonObject !=nil){ 
    // NSString *errorCode=[NSMutableString stringWithFormat:@"%@",[jsonObject objectForKey:@"response"]]; 


     if(![[jsonObject objectForKey:@"#data"] isEqual:@""]){ 

      NSMutableArray *array=[jsonObject objectForKey:@"#data"]; 
      // NSLog(@"array: %@",array); 
      NSLog(@"array: %d",array.count); 

      int k = 0; 
      for(int z = 0; z<array.count;z++){ 

       NSString *strfd = [NSString stringWithFormat:@"%d",k]; 
       NSDictionary *dicr = jsonObject[@"#data"][strfd]; 
       k=k+1; 
       // NSLog(@"dicr: %@",dicr); 
       NSLog(@"Firstname - Lastname : %@ - %@", 
        [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_first_name"]], 
        [NSMutableString stringWithFormat:@"%@",[dicr objectForKey:@"user_last_name"]]); 
      } 

      } 

    } 

你可以看到控制檯輸出如下:

Firstname - Lastname : Chandra Bhusan - Pandey

Firstname - Lastname : Kalaiyarasan - Balu

Firstname - Lastname : (null) - (null)

Firstname - Lastname : Girija - S

Firstname - Lastname : Girija - S

Firstname - Lastname : (null) - (null)