[toc]
最近公司產(chǎn)品有一個(gè)新的需求鸦致,將本地編輯一半的視頻保存到草稿箱。拿到這個(gè)需求锭碳,我第一反應(yīng)就是使用數(shù)據(jù)庫(kù)袁稽。但是忽然又想嘗試一種新的方式來(lái)記錄這個(gè)編輯狀態(tài),那就是通過(guò)
NSJSONSerialization
這個(gè)類擒抛,將對(duì)象轉(zhuǎn)換成JSON
保存到本地运提。
OK! Talk is cheep, show me the code!
1. 如何判斷一個(gè)對(duì)象可否轉(zhuǎn)換成json格式
首先,我們一起觀察一下這個(gè)類的方法:
/* Returns YES if the given object can be converted to JSON data, NO otherwise. The object must have the following properties:
- Top level object is an NSArray or NSDictionary
- All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
- All dictionary keys are NSStrings
- NSNumbers are not NaN or infinity
Other rules may apply. Calling this method or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
*/
+ (BOOL)isValidJSONObject:(id)obj;
該方法可以判斷傳入的對(duì)象是否可以轉(zhuǎn)換為JSON數(shù)據(jù)闻葵,返回NO 則該對(duì)象不能被轉(zhuǎn)換民泵。
關(guān)于轉(zhuǎn)換為JSON的對(duì)象,官方要求有幾點(diǎn)
- 頂級(jí)對(duì)象必須是NSArray 或者是 NSDictionary槽畔。
- 所有保存的對(duì)象必須是 NSString栈妆,NSNumber,NSArray厢钧,NSDictionary鳞尔,or NSNull。
- 字典的Key早直,必須是字符串寥假。
- NSNumber對(duì)象類型,不能是NaN或無(wú)窮的霞扬。
舉個(gè)栗子:我們模仿服務(wù)器返回格式糕韧,自己包裝了這么一個(gè)字典,來(lái)喻圃,判斷一下是否符合規(guī)則吧萤彩。
NSMutableDictionary *video = [NSMutableDictionary dictionary];
video[@"videoName"] = @"我的戰(zhàn)爭(zhēng)";
video[@"videoCover"] = @"http://www.imageUrl.com";
video[@"time"] = @"1098";
NSMutableArray *videoArr = [NSMutableArray array];
[videoArr addObject:video];
NSMutableDictionary *dicData = [NSMutableDictionary dictionary];
dicData[@"code"] = @"200";
dicData[@"reason"] = @"success";
dicData[@"result"] = videoArr;
BOOL isValid = [NSJSONSerialization isValidJSONObject:dicData];
NSLog(@"%d", isValid);
2. 寫(xiě)入json數(shù)據(jù)
我們?cè)倏吹诙€(gè)用到的方法:
/* Write JSON data into a stream. The stream should be opened and configured. The return value is the number of bytes written to the stream, or 0 on error. All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
*/
+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;
這個(gè)方法可以將一個(gè)JSON數(shù)據(jù)寫(xiě)入一個(gè)流中, 在寫(xiě)入之前需要將流打開(kāi)并初始化斧拍。返回?cái)?shù)據(jù)是寫(xiě)入流中的字節(jié)數(shù)雀扶。如果發(fā)生錯(cuò)誤,返回0肆汹。
// 首先初始化一下數(shù)據(jù)流愚墓, path 是本地沙盒中的一個(gè)路徑
NSOutputStream *outStream = [[NSOutputStream alloc] initToFileAtPath:path append:NO];
// 打開(kāi)數(shù)據(jù)流
[outStream open];
// 執(zhí)行寫(xiě)入方法,并接收寫(xiě)入的數(shù)據(jù)量
NSInteger length = [NSJSONSerialization writeJSONObject:dic toStream:outStream options:NSJSONWritingPrettyPrinted error:&error];
NSLog(@"write %ld bytes",(long)length);
// 關(guān)閉數(shù)據(jù)流昂勉, 寫(xiě)入完成
[outStream close];
結(jié)果寫(xiě)入成功啦浪册!
{
"reason" : "success",
"result" : [
{
"time" : "1098",
"videoName" : "我的戰(zhàn)爭(zhēng)",
"videoCover" : "http:\/\/www.imageUrl.com"
}
],
"code" : "200"
}
3. 讀取json數(shù)據(jù)
然后我們可以利用如下方法取出來(lái)
NSMutableDictionary *jsonDictionary;
//use JSONObjectWithStream
NSInputStream *inStream = [[NSInputStream alloc] initWithFileAtPath:path];
[inStream open];
id streamObject = [NSJSONSerialization JSONObjectWithStream:inStream options:NSJSONReadingAllowFragments error:&error];
if ([streamObject isKindOfClass:[NSDictionary class]]) {
jsonDictionary = (NSMutableDictionary *)streamObject;
}
[inStream close];
打印jsonDictionary
就可以看到,已經(jīng)完整的取出來(lái)啦硼啤。