今天在項目里面遇到需要像服務器回傳json格式的情況 以前沒有遇到過 下面是解決方法 當然 這里的方法不包含 回去的參數里面有id這種特殊的處理哈 這種方法以后再研究吧
// JSONHelper.h
@interface JSONHelper : NSObject
+ (NSData *)toJSONData:(id)theData;
#import "JSONHelper.h"
@implementation JSONHelper
+ (NSData *)toJSONData:(id)theData {
JSONHelper *helper = [[JSONHelper alloc]init];
return [helper toJSONData:theData];
}
// 將字典或者數組轉化為JSON串
- (NSData *)toJSONData:(id)theData{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
options:NSJSONWritingPrettyPrinted
error:&error];
if ([jsonData length] > 0 && error == nil){
return jsonData;
}else{
return nil;
}
}
使用時在需要json反序列化的類里面引入頭文件
字典的使用方法
NSDictionary *dict = @[@"1",@"2",@"3",@"4"];
NSData *json = [JSONHelper toJSONData: dict];
回傳參數中
NSDictionary *params = @{@"jsonData":json};
在將data數據作為數組使用的時候 這種時候是什么時候呢 我們在使用tableview的時候 習慣將下載的數據把json數據作為model存放在數組中 當我們使用的時候 首先要從數組中遍歷出需要的字典 然后再進行操作
//json格式轉化
NSMutableArray *temp = [NSMutableArray array];
for (int i = 0; i < _touristList.count; i++) {
AdjustTouristModel *touristModel = [_touristList objectAtIndex:i];
NSString *price = [NSString stringWithFormat:@"%ld", (long)touristModel.price];
NSDictionary *tempDict = @{@"tourist_id":touristModel.tourist_id,@"receive": price};
[temp addObject:tempDict];
}
NSData *tourists = [JSONHelper toJSONData:temp];
NSDictionary *param = @{@"touristsReceive":tourists};
[_adjustPassParams setValuesForKeysWithDictionary:param];