最近被問到iOS中JSON轉(zhuǎn)Object的過程中如果服務(wù)端給的JSON是不全的該如何處理雳灵,會不會造成崩潰棕所?
經(jīng)過我的測試,是不會造成崩潰的悯辙,只是結(jié)果為nil琳省,但是在object --> JSON的過程中發(fā)生錯誤的話,系統(tǒng)是會拋出異常躲撰,也就是崩潰的针贬。下面可以仔細(xì)看一下iOS提供的API。
JSON --> Object
BOOL isFool = YES;
NSString *json = @"{\"users\":[\"Jack\",\"Pinkman\"]}";
if (isFool) {
json = @"{\":[\"Jack\",\"Pinkman\"]}";
}
// json --> dict
NSData *j_data = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *j_err = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:j_data options:NSJSONReadingMutableContainers error:&j_err];
if (dict && !j_err) {
NSLog(@"success %@",dict);
} else {
/*
json --> dict的過程中產(chǎn)生錯誤并不會崩潰
*/
NSLog(@"fail %@",j_err);
}
轉(zhuǎn)換關(guān)鍵的是[NSJSONSerialization JSONObjectWithData:options:error:]拢蛋,看一下Apple給的注釋
Create a Foundation object from JSON data. If an error occurs during the parse, then the error parameter will be set and the result will be nil.
--翻譯--
根據(jù)JSON data創(chuàng)建一個Foundation Object桦他。如果在轉(zhuǎn)化的過程中發(fā)生了錯誤,結(jié)果為nil谆棱,error將會被賦值文狱。
(省略掉了一些關(guān)于options參數(shù)的解釋坟募,整個注釋中并沒有提到會拋出異常)
所以結(jié)論是即使后端返回的JSON數(shù)據(jù)是異常的直秆,iOS客戶端在轉(zhuǎn)化的過程中并不會崩潰,也無需做特殊處理坪郭。
Object --> JSON
先看Apple提供API的注釋
Generate JSON data from a Foundation object. If the object will not produce valid JSON then an exception will be thrown. If an error occurs, the error parameter will be set and the return value will be nil.
--翻譯--
根據(jù)一個Foundation object生成JSON data。如果object不是符合規(guī)范的JSON歪沃,異常將會被拋出绸罗。如果發(fā)生了異常,結(jié)果為nil育灸,error會被賦值昵宇。
(Apple提示了這個過程中如果發(fā)生錯誤是會拋出異常崩潰的)
那么該如何規(guī)避這種崩潰呢砸喻?NSJSONSerialization中提供了+(BOOL)isValidJSONObject:用來檢測object是否能被轉(zhuǎn)成JSON割岛,只要先用這個判斷就可以了,代碼如下:
// 一個自定義的類惠爽,自己寫一下就行
BreakingBad *white = [[BreakingBad alloc] init];
white.name = @"White";
NSDictionary *origDict = @{
@"users":@[@"Jessy",@"Pinkman"],
@"guity":[NSNull null],
@"object":white,
};
BOOL isValid = [NSJSONSerialization isValidJSONObject:origDict];
if (isValid) {
NSError *o_err = nil;
NSData *o_data = [NSJSONSerialization dataWithJSONObject:origDict options:NSJSONWritingFragmentsAllowed error:&o_err];
if (o_data && !o_err) {
NSString *str = [[NSString alloc] initWithData:o_data encoding:NSUTF8StringEncoding];
NSLog(@"obj --> json success %@",str);
} else {
NSLog(@"obj --> json fail %@",o_err);
}
} else {
NSLog(@"obj --> json fail, obj is not valid");
}