Reputation: 789
I need to write JSON data to a file using Objective-C. My data looks something like this:
data = {
"NrObjects" : "7",
"NrScenes" : "5",
"Scenes" : [
{ "dataType" : "label", "position" : [20, 20, 300, 300], "value" : "Hello" },
{ "dataType" : "label", "position" : [20, 60, 300, 300], "value" : "Hi There" }
]
}
It may get more complex than this, but what I need to know is whether I can do this with Obj-C, i.e., create an object of this form, write the data to a file, and read it back.
Upvotes: 22
Views: 13005
Reputation: 4667
write:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];
read:
NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Upvotes: 6
Reputation: 13459
There is a class specifically made for this, its called NSJSONSerialization.
You read it like this:
NSArray* jsonResponse = [NSJSONSerialization JSONObjectWithData:theResponse
options:kNilOptions
error:&error];
and write it like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDetails
options:kNilOptions
error:&error];
Upvotes: 31