Joey
Joey

Reputation: 7527

saving JSON object in iOS

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?

Upvotes: 1

Views: 2384

Answers (2)

Eric V
Eric V

Reputation: 1170

AsiHTTP allows you to cache your requests. It implements the features that you need

Upvotes: 0

Daniel Dickison
Daniel Dickison

Reputation: 21882

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:

  • Use +[NSKeyedArchiver archiveRootObject:toFile:].
  • Use SBJSON to turn the data back into JSON and store the JSON string as UTF-8 data.
  • Save it out as a plist using +[NSPropertyListSerialization dataFromPropertyList:format:errorDescription:].

Upvotes: 2

Related Questions