iOS json的反序列化

今天在項目里面遇到需要像服務器回傳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];
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • iOS網絡架構討論梳理整理中。。。 其實如果沒有APIManager這一層是沒法使用delegate的,畢竟多個單...
    yhtang閱讀 5,259評論 1 23
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,532評論 25 708
  • 這是一個物質飛速發展的時代,無數東西被制造出來,又輕易地被拋棄;這是一個娛樂至死的時代,香港島上一閃一閃亮晶...
    污小姐閱讀 1,028評論 3 7
  • 2016年07月06日 鄉村夏夜 夜色涼如水,蟲輕吟似夢。卸下了所有的風塵,我坐在后院,風吹過我的腳,我把拖鞋放到...
    重獲自由閱讀 205評論 0 1