在 iOS 中保存 JSON 对象
我使用 SBJsonParser 来解析从服务器查询的大型 json 响应。我想使用时间戳方法来知道什么时候我实际上必须重新获取并重新解析所有数据,所以我想知道如何在不需要的时候保存数据请求大型 JSON 包来刷新我的数据。
我想我应该使用 NSCoding 协议并大致如下进行归档:
// alloc nsdata obj
NSMutableData *data = [[[NSMutableData alloc] init] autorelease];
// create archiver
NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease];
// archive whiteboard
[archiver encodeObject:mSaveData forKey:@"Data"];
[archiver finishEncoding];
[data writeToFile:dataPath atomically:YES];
但是有没有一种简单的方法来编码这个实际上是 NSDictionaries 的 NSArray 的 JSON 对象,或者我是否必须仔细地编码该对象中的每个字段?
也许有一种更简单的方法,比如将 json 对象本身保存为字符串(在使用 objectWithData 方法解析它之前)并在每次应用程序加载并想要使用本地副本时重新解析它?
I use SBJsonParser for parsing a large json response I query from a server. I'd like to use a timestamp approach to know when I actually have to re-obtain and re-parse all the data again, so I'd like to know how I can save my data for those times I don't need to request the large JSON package to refresh my data.
I'm thinking I should be using the NSCoding protocol and archiving roughly like the following:
// alloc nsdata obj
NSMutableData *data = [[[NSMutableData alloc] init] autorelease];
// create archiver
NSKeyedArchiver *archiver = [[[NSKeyedArchiver alloc] initForWritingWithMutableData:data] autorelease];
// archive whiteboard
[archiver encodeObject:mSaveData forKey:@"Data"];
[archiver finishEncoding];
[data writeToFile:dataPath atomically:YES];
but is there a simple way to encode this JSON object that is really an NSArray of NSDictionaries, or do I have to meticulously encode each field within this object?
Maybe there is a simpler way altogether, like saving the json object itself as a string (before it is parsed with the objectWithData method) and re-parsing it each time the app loads and wants to use the local copy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于你想要保存的数据只是 NSArrays、NSDictionaries,大概还有 NSStrings 和 NSNumbers 之类的东西,我不明白为什么你需要“精心编码每个字段”。您使用 NSKeyedArchiver 执行此操作的方式是有效的,并且您不需要任何进一步的代码来保存。其他一些选项:
+[NSKeyedArchiver archiveRootObject:toFile:]
。+[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:]
将其保存为 plist。Since the data you want to save are just NSArrays, NSDictionaries, and presumably things like NSStrings and NSNumbers, I don't see why you need to "meticulously encode each field". The way you did it with NSKeyedArchiver is valid, and you don't need any further code to save. Some other options:
+[NSKeyedArchiver archiveRootObject:toFile:]
.+[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:]
.AsiHTTP 允许您缓存您的请求。它实现了您需要的功能
AsiHTTP allows you to cache your requests. It implements the features that you need