iOS 将NSArray、NSDictionary转换为JSON格式进行网络传输

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  
原文地址:https://www.cnblogs.com/zxykit/p/6164049.html