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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,337评论 30 472
  • 站在前辈的肩膀上前行 UIKit框架和Foundation框架 所有的Mac OS X和IOS程序都是由大量的对象...
    zysmoon阅读 12,817评论 0 16
  • 最近一朋友正准备跳槽,就从各处搜索整理一些基础,便于朋友复习,也便于自己复习查看. 1. 回答person的ret...
    smile丽语阅读 5,779评论 0 7
  • 我的梦已经开始发芽, 打开那扇关闭了多年的窗, 让阳光撒满心房。 像破茧的蝴蝶, 以树叶为船白云为帆, 挥舞着带着...
    陶韵阅读 1,482评论 0 0
  • 一个永远都不知道长大的人 一句珍惜的话都不会说 阴影重重且谎话连篇 计划的都没有实现 自卑充斥着内心 你认识的是假...
    QueenLaurel阅读 1,436评论 0 0