iOS 將NSArray、NSDictionary轉換為JSON格式進行網路傳輸

來源:互聯網
上載者:User

標籤:pen   property   import   time   str   sign   參數   err   serial   

http://blog.csdn.net/worldzhy/article/details/49982491

 

將NSArray、NSDictionary轉換為JSON格式進行網路傳輸,是經常用到的,但是iOS沒有提供方便的方法庫。我們類比一個執行個體,假設我們需要把一個自訂的一個模型(只有若干屬性的Class)的數組轉為一個JSON字串,作為後端需要的一個參數傳給後端,下面給出了實現方法:

 

 

 

[objc] view plain copy 
  1. //HSPictureModel數組轉為json  
  2. - (NSString *)pictureArrayToJSON:(NSArray *)picArr {  
  3.       
  4.     if (picArr && picArr.count > 0) {  
  5.           
  6.         NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];  
  7.           
  8.         for (HSPictureModel *model in picArr) {  
  9.             NSData *jsonData = [Object2Json getJSON:model options:NSJSONWritingPrettyPrinted error:nil];  
  10.             NSString *jsonText = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];  
  11.               
  12.             [arr addObject:jsonText];  
  13.         }  
  14.           
  15.         return [self objArrayToJSON:arr];  
  16.     }  
  17.       
  18.     return nil;  
  19. }  
  20.   
  21. 上方這個方法<span style="font-size:18px;">第一步,將一個model轉換為JSON字串,然後將數組中的這些字串拼接起來,得到最終的JSON字串。實現了我們的目的。其中用到的Object2Json的代碼附在文章最下面。  
  22. </span>  
  23.   
  24. //把多個json字串轉為一個json字串  
  25. - (NSString *)objArrayToJSON:(NSArray *)array {  
  26.       
  27.     NSString *jsonStr = @"[";  
  28.       
  29.     for (NSInteger i = 0; i < array.count; ++i) {  
  30.         if (i != 0) {  
  31.             jsonStr = [jsonStr stringByAppendingString:@","];  
  32.         }  
  33.         jsonStr = [jsonStr stringByAppendingString:array[i]];  
  34.     }  
  35.     jsonStr = [jsonStr stringByAppendingString:@"]"];  
  36.       
  37.     return jsonStr;  
  38. }  

 

 

以上,我們實現了資料從用戶端傳到後台時可能需要的轉換,下面再看一下,如何把後台傳過來的JSON形式的字串,解析為用戶端認識的NSArray或者NSDictionary。

 

[objc] view plain copy 
  1. //json字串轉為數組  
  2. - (NSArray *)stringToJSON:(NSString *)jsonStr {  
  3.     if (jsonStr) {  
  4.         id tmp = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];  
  5.           
  6.         if (tmp) {  
  7.             if ([tmp isKindOfClass:[NSArray class]]) {  
  8.                   
  9.                 return tmp;  
  10.                   
  11.             } else if([tmp isKindOfClass:[NSString class]]  
  12.                     || [tmp isKindOfClass:[NSDictionary class]]) {  
  13.                   
  14.                 return [NSArray arrayWithObject:tmp];  
  15.                   
  16.             } else {  
  17.                 return nil;  
  18.             }  
  19.         } else {  
  20.             return nil;  
  21.         }  
  22.           
  23.     } else {  
  24.         return nil;  
  25.     }  
  26. }  


這個獨立的方法可以實現後端JSON字串轉為NSArray或NSDictionary的功能。

 

 

最後,附上Object2Json類的實現,該實現摘抄自網路。

 

[objc] view plain copy 
    1. #import "Object2Json.h"  
    2. #import <objc/runtime.h>  
    3.   
    4. @implementation Object2Json  
    5. + (NSDictionary*)getObjectData:(id)obj  
    6. {  
    7.     NSMutableDictionary *dic = [NSMutableDictionary dictionary];  
    8.     unsigned int propsCount;  
    9.     objc_property_t *props = class_copyPropertyList([obj class], &propsCount);  
    10.     for(int i = 0;i < propsCount; i++)  
    11.     {  
    12.         objc_property_t prop = props[i];  
    13.           
    14.         NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];  
    15.         id value = [obj valueForKey:propName];  
    16.         if(value == nil)  
    17.         {  
    18.             value = [NSNull null];  
    19.         }  
    20.         else  
    21.         {  
    22.             value = [self getObjectInternal:value];  
    23.         }  
    24.         [dic setObject:value forKey:propName];  
    25.     }  
    26.     return dic;  
    27. }  
    28.   
    29.   
    30. + (NSData*)getJSON:(id)obj options:(NSJSONWritingOptions)options error:(NSError**)error  
    31. {  
    32.     return [NSJSONSerialization dataWithJSONObject:[self getObjectData:obj] options:options error:error];  
    33. }  
    34.   
    35. + (id)getObjectInternal:(id)obj  
    36. {  
    37.     if([obj isKindOfClass:[NSString class]]  
    38.        || [obj isKindOfClass:[NSNumber class]]  
    39.        || [obj isKindOfClass:[NSNull class]])  
    40.     {  
    41.         return obj;  
    42.     }  
    43.       
    44.     if([obj isKindOfClass:[NSArray class]])  
    45.     {  
    46.         NSArray *objarr = obj;  
    47.         NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];  
    48.         for(int i = 0;i < objarr.count; i++)  
    49.         {  
    50.             [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];  
    51.         }  
    52.         return arr;  
    53.     }  
    54.       
    55.     if([obj isKindOfClass:[NSDictionary class]])  
    56.     {  
    57.         NSDictionary *objdic = obj;  
    58.         NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];  
    59.         for(NSString *key in objdic.allKeys)  
    60.         {  
    61.             [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];  
    62.         }  
    63.         return dic;  
    64.     }  
    65.     return [self getObjectData:obj];  
    66. }  
    67. @end  

iOS 將NSArray、NSDictionary轉換為JSON格式進行網路傳輸

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.