[toc]
最近公司產品有一個新的需求,將本地編輯一半的視頻保存到草稿箱。拿到這個需求,我第一反應就是使用數據庫。但是忽然又想嘗試一種新的方式來記錄這個編輯狀態,那就是通過
NSJSONSerialization
這個類,將對象轉換成JSON
保存到本地。
OK! Talk is cheep, show me the code!
1. 如何判斷一個對象可否轉換成json格式
首先,我們一起觀察一下這個類的方法:
/* 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;
該方法可以判斷傳入的對象是否可以轉換為JSON數據,返回NO 則該對象不能被轉換。
關于轉換為JSON的對象,官方要求有幾點
- 頂級對象必須是NSArray 或者是 NSDictionary。
- 所有保存的對象必須是 NSString,NSNumber,NSArray,NSDictionary,or NSNull。
- 字典的Key,必須是字符串。
- NSNumber對象類型,不能是NaN或無窮的。
舉個栗子:我們模仿服務器返回格式,自己包裝了這么一個字典,來,判斷一下是否符合規則吧。
NSMutableDictionary *video = [NSMutableDictionary dictionary];
video[@"videoName"] = @"我的戰爭";
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. 寫入json數據
我們再看第二個用到的方法:
/* 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;
這個方法可以將一個JSON數據寫入一個流中, 在寫入之前需要將流打開并初始化。返回數據是寫入流中的字節數。如果發生錯誤,返回0。
// 首先初始化一下數據流, path 是本地沙盒中的一個路徑
NSOutputStream *outStream = [[NSOutputStream alloc] initToFileAtPath:path append:NO];
// 打開數據流
[outStream open];
// 執行寫入方法,并接收寫入的數據量
NSInteger length = [NSJSONSerialization writeJSONObject:dic toStream:outStream options:NSJSONWritingPrettyPrinted error:&error];
NSLog(@"write %ld bytes",(long)length);
// 關閉數據流, 寫入完成
[outStream close];
結果寫入成功啦!
{
"reason" : "success",
"result" : [
{
"time" : "1098",
"videoName" : "我的戰爭",
"videoCover" : "http:\/\/www.imageUrl.com"
}
],
"code" : "200"
}
3. 讀取json數據
然后我們可以利用如下方法取出來
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
就可以看到,已經完整的取出來啦。