iOS开发集锦小知识点好东西

iOS 将对象序列化成json,写入本地文件

2017-09-17  本文已影响34人  徊家喂猪

[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的对象,官方要求有几点

举个栗子:我们模仿服务器返回格式,自己包装了这么一个字典,来,判断一下是否符合规则吧。

    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就可以看到,已经完整的取出来啦。

上一篇下一篇

猜你喜欢

热点阅读