iOS開發(fā)Json數(shù)據(jù)與模型對象的相互轉(zhuǎn)換

在iOS開發(fā)中Json數(shù)據(jù)是我們再熟悉不過的數(shù)據(jù)格式了,這篇文章主要講述的是Json數(shù)據(jù)與模型對象之間的相互轉(zhuǎn)換關(guān)系。

第一種:模型對象轉(zhuǎn)Json數(shù)據(jù)格式。

? ? ? ? 首先我們講一下模型對象如何轉(zhuǎn)換成Json數(shù)據(jù),這個用的不是太頻繁,但是當(dāng)我們需要將Json數(shù)據(jù)上傳到服務(wù)器的時候,我們就需要將我們的模型對象轉(zhuǎn)換成Json數(shù)據(jù)了。其實說起來也挺簡單的,主要是注意轉(zhuǎn)json的對象是數(shù)組或字典,不可以是自定義的對象。

創(chuàng)建model類:



代碼:



????????? ? ? ?/** 模型轉(zhuǎn)Json */

????????? - (void)modelTranstoJson{

????????????//Model? ->? NSDictionary? -> Json

????????????BXMovieModel *videoModel = [[BXMovieModel alloc]init];

????????????????videoModel.name = @"菊花俠大戰(zhàn)桃花怪";

????????????videoModel.videoId = @"1";

????????????videoModel.videoURL = @"http://blog.sina.com.cn/marsliudev";

????????????videoModel.imageURL = @"http://blog.sina.com.cn/marsliudev";

????????//模型? 轉(zhuǎn) 字典

????????NSArray *array = @[videoModel];

????????NSDictionary *dic = [videoModel? dictionaryWithValuesForKeys:@[@"name",@"videoId",@"videoURL",@"imageURL"]];

????????NSLog(@"+++++++++++++%@",dic);

????????//要求轉(zhuǎn)json的對象 是數(shù)組或字典 不可以是自定義的對象

????????NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

????????NSString *tempStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

????????NSLog(@"--------%@",tempStr);

????????}????



第二種:從網(wǎng)絡(luò)獲取Json數(shù)據(jù)進(jìn)行解析,字典轉(zhuǎn)模型。




代碼:

viewController.m內(nèi)代碼:

主要就是請求 json數(shù)據(jù)

BXToolManager *manager = [[BXToolManager alloc]init];? ?

[manager sendRequestWithUrl:@"http://api2.juheapi.com/jztk/query?subject=1&model=c1&key=f9a989c45f5f63da75360b7e86004842&testType=order"];

_dataArrayM = [[BXToolManager getTestArray] mutableCopy];

BXToolManager.m中代碼:

- (void)sendRequestWithUrl:(NSString *)urlstr{

dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSURL *url = [NSURL URLWithString:urlstr];

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

if (!error) {

dispatch_async(dispatch_get_main_queue(), ^{

NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

NSArray *dataArray = dataDic[@"result"];

[[NSUserDefaults standardUserDefaults]setObject:dataArray forKey:@"dic"];

});

}else{

NSLog(@"%@",error.userInfo);

}

}];

[dataTask resume];

});

}

+(NSArray *)getTestArray{

NSMutableArray *muArray=[NSMutableArray array];

NSArray *array=[[NSUserDefaults standardUserDefaults]objectForKey:@"dic"];

for (NSDictionary *dic in array) {

[muArray addObject:[BXJsonModel initWithDictionary:dic]];

}

return muArray;

}

BXJsonModel.m中代碼:

-(instancetype)initWithDictionaty:(NSDictionary *)dic

{

if (self=[super init]) {

self.answer=dic[@"answer"];

self.explains=dic[@"explains"];

self.item1=dic[@"item1"];

self.item2=dic[@"item2"];

self.item3=dic[@"item3"];

self.item4=dic[@"item4"];

self.question=dic[@"question"];

self.url=dic[@"url"];

}

return self;

}

+(instancetype)initWithDictionary:(NSDictionary *)dic

{

return [[BXJsonModel alloc]initWithDictionaty:dic];

}

既然你能夠看到這里,再說個當(dāng)時在請求json數(shù)據(jù)時遇到的事情,一開始我寫json數(shù)據(jù)網(wǎng)絡(luò)請求的時候,實用的是下面的代碼,也能夠成功的請求到數(shù)據(jù),可是后來想想這個方法還是最好別用,如果請求的API不適公共資源,將會獲取不到數(shù)據(jù)。

/*

*? 這種方法也可以獲取到數(shù)據(jù) ,只不過獲取到的數(shù)據(jù)資源是公共資源,如果資源收到限制的API將無法請求到資源

*

*/

- (void)sendRequestWithUrl:(NSString *)urlstr

{

dispatch_async(dispatch_get_global_queue(0, 0), ^{

NSURL *url = [NSURL URLWithString:urlstr];

NSData *data = [NSData dataWithContentsOfURL:url];

dispatch_async(dispatch_get_main_queue(), ^{

NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

NSArray *dataArray = dataDic[@"result"];

[[NSUserDefaults standardUserDefaults]setObject:dataArray forKey:@"dic"];

});

});

}


好了,就寫這么多,不吹牛逼了,繼續(xù)敲代碼。喜歡的點一波關(guān)注 。不懂得可以發(fā)郵件給我mars_liu_dev@163.com。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容